diff --git a/MCP.md b/MCP.md index 69124c2..4299235 100644 --- a/MCP.md +++ b/MCP.md @@ -406,7 +406,7 @@ Piper's stderr is reported on failure. | tool | args | does | |---|---|---| -| `export_start` | **out**, preset (an `export_presets` id; explicit args override it), loudness (-30 to -5 LUFS, the integrated target; the true peak holds at the preset's ceiling or -1 dBTP, the gain is cut back and never a limiter), format (mp4, av1, av1-mp4, hevc, hevc-mp4, webm, wav, flac, mp3, ogg, m4a, opus, prores, png_sequence, still, gif), gif_width (320/480/640/720, default 480), gif_fps (1-60, default 15), gif_loop (default true), range, size, fit, bitrate_kbps, qp (0-51, a constant quantiser instead of a bitrate: the hardware seat for H.264, HEVC and AV1, and software HEVC; software H.264 and AV1 refuse it; not with bitrate_kbps), audio_kbps (128/192/256/320, and 384 for AAC only: mp4, av1, av1-mp4, hevc, hevc-mp4, m4a), bit_depth (8\|10; 10 is AV1 and HEVC only), prores_profile (proxy\|lt\|standard\|hq\|4444\|4444xq; format `prores`, a `.mov`), hdr (off\|pq\|hlg; HEVC only, implies 10-bit), hevc_speed (default\|fast\|faster; HEVC only: fast is about 1.2-1.6x quicker for 0-3% more bits, faster about 1.5-2x quicker for up to 27% more), audio_bit_depth (16\|24; ProRes sound), chapters (default true; `"markers"` writes the comment markers as the chapters), intra_only, seat (auto\|hardware\|software), subtitles, burn_captions, overwrite | starts an export; returns `job:` at once. The reply counts the chapters written (`3 chapters`) and, for an AV1 or HEVC file, its depth (`output 10-bit, from the source`) · `queue` (true: line the export up behind the others -- it keeps its own copy of the timeline as it is now, so later edits do not change it, and starts when every earlier export has finished, one encode at a time, polled or not; `export_status` shows it as `waiting`; default false starts at once beside any others) | +| `export_start` | **out**, preset (an `export_presets` id; explicit args override it), loudness (-30 to -5 LUFS, the integrated target; the true peak holds at the preset's ceiling or -1 dBTP, the gain is cut back and never a limiter), format (mp4, av1, av1-mp4, hevc, hevc-mp4, webm, wav, flac, mp3, ogg, m4a, opus, prores, png_sequence, still, gif), gif_width (320/480/640/720, default 480), gif_fps (1-60, default 15), gif_loop (default true), range, size, fit, bitrate_kbps, qp (0-51, a constant quantiser instead of a bitrate: the hardware seat for H.264, HEVC and AV1, and software HEVC; software H.264 and AV1 refuse it; not with bitrate_kbps), keyframe_s (0.1-10 seconds between key frames of the picture, default the encoder's two; not with intra_only), faststart (true lays an mp4, hevc-mp4, av1-mp4 or m4a out moov-first so it plays before it is fully read; other formats refused), audio_kbps (128/192/256/320, and 384 for AAC only: mp4, av1, av1-mp4, hevc, hevc-mp4, m4a), bit_depth (8\|10; 10 is AV1 and HEVC only), prores_profile (proxy\|lt\|standard\|hq\|4444\|4444xq; format `prores`, a `.mov`), hdr (off\|pq\|hlg; HEVC only, implies 10-bit), hevc_speed (default\|fast\|faster; HEVC only: fast is about 1.2-1.6x quicker for 0-3% more bits, faster about 1.5-2x quicker for up to 27% more), audio_bit_depth (16\|24; ProRes sound), chapters (default true; `"markers"` writes the comment markers as the chapters), intra_only, seat (auto\|hardware\|software), subtitles, burn_captions, overwrite | starts an export; returns `job:` at once. The reply counts the chapters written (`3 chapters`) and, for an AV1 or HEVC file, its depth (`output 10-bit, from the source`) · `queue` (true: line the export up behind the others -- it keeps its own copy of the timeline as it is now, so later edits do not change it, and starts when every earlier export has finished, one encode at a time, polled or not; `export_status` shows it as `waiting`; default false starts at once beside any others) | | `export_presets` | – | lists the export presets (id, label, format, bitrate_kbps, audio_kbps, size, bit_depth, prores_profile, hdr, loudness): youtube_1080p/1080p60/1080p_hevc/4k/4k60/4k_hevc, shorts_reels, podcast, podcast_ogg and podcast_opus (-16 LUFS, -1 dBTP), archive (10-bit AV1 mkv), archive_prores (ProRes 422 HQ .mov), hdr10_hevc (10-bit HEVC mp4 tagged PQ), archive_flac, archive_wav | | `export_captions` | format (`srt` or `vtt`, required unless chapters), path, overwrite, chapters | writes the timeline's captions (every cue on the subtitle lanes, in start order) as SRT or WebVTT; picture and empty cues are left out. Without `path`: ` edit.` in the Videos folder. Refuses an existing file unless `overwrite` is true, and writes nothing when there are no captions. `chapters: true` writes nothing and returns the chapter markers as the YouTube description listing (`00:00 Intro`, one line each), the text File > Copy chapters copies, as the reply text and as JSON (`chapters` lines, `text`, `warnings`) | | `proxies` | action (`status`, the default, `make`, `cancel` or `delete`), source (`src:`, a list or `"all"`) | the editing copies (proxies) of sources. `status` shows each source's state (ready, making with its percent, off, not needed for a sound or still, or why a stand-in failed). `make` starts one in the background and turns that film's switch back on; a film that plays at speed on this machine needs none, and says so. `cancel` stops one being made and leaves the film off, as the Proxies switch on a library row does. `delete` removes the stand-in and keeps the film off. With `auto_proxies` on, each `media_import` starts its stand-ins the same way | diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs index 4ea8c10..bddf7a6 100644 --- a/crates/app/src/export_ui.rs +++ b/crates/app/src/export_ui.rs @@ -774,6 +774,8 @@ pub(crate) fn export_settings( hdr: HdrOutput::default(), hevc_speed: None, gif: GifSettings::default(), + keyframe_s: None, + faststart: false, } } diff --git a/crates/engine-hw/src/enc_ec.rs b/crates/engine-hw/src/enc_ec.rs index b133543..23d02e5 100644 --- a/crates/engine-hw/src/enc_ec.rs +++ b/crates/engine-hw/src/enc_ec.rs @@ -48,6 +48,8 @@ pub(crate) struct EcOpen { pub rate: SeatRate, /// Every picture an IDR: what a proxy is coded with (see `gop_limit`). pub intra_only: bool, + /// Pictures between key frames; `None` is `gop_limit`'s. + pub gop: Option, /// Colour description for the VUI as `(primaries, transfer, matrix, full)`. pub colour: Option<(u8, u8, u8, bool)>, } @@ -62,6 +64,7 @@ impl EcEncSession { fps_den, rate, intra_only, + gop, colour, } = req; // NV12 chroma is half resolution, so odd dimensions have no packing; @@ -84,7 +87,10 @@ impl EcEncSession { if let SeatRate::Bitrate(bitrate) = rate { config.bitrate = u32::try_from(bitrate).unwrap_or(u32::MAX); } - config.gop_size = u32::from(crate::gop_limit(framerate, intra_only)); + config.gop_size = gop.unwrap_or_else(|| match (codec, intra_only) { + (EncCodec::H265, false) => framerate, + _ => u32::from(crate::gop_limit(framerate, intra_only)), + }); config.rate_control = match (codec, rate) { (EncCodec::Av1, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp: qp.min(51) * 255 / 51 }, (_, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp }, diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index ae41004..ab46039 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -820,6 +820,7 @@ pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option fps_den: open.fps_den, rate: open.rate, intra_only, + gop: open.gop, colour, }) } @@ -868,6 +869,7 @@ mod tests { fps_den: 1, rate: SeatRate::Bitrate(2_000_000), intra_only: true, + gop: None, colour: None, }; // No VA-API on this machine: nothing to encode, nothing to claim. @@ -949,6 +951,7 @@ mod tests { fps_den: 1, rate: SeatRate::Bitrate(2_000_000), intra_only: true, + gop: None, colour: None, }; let Some(mut session) = EcEncSession::open(open) else { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 12abe05..b419712 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -328,6 +328,11 @@ impl Format { matches!(self, Self::Hevc | Self::HevcMp4) } + /// Whether the file is an mp4 box file (mp4, hevc-mp4, av1-mp4 or m4a), which is what faststart lays out. + pub fn is_mp4_family(self) -> bool { + matches!(self, Self::Mp4 | Self::HevcMp4 | Self::Av1Mp4 | Self::M4a) + } + /// Whether the picture is ProRes in a QuickTime file ([`Format::ProRes`]). pub fn is_prores(self) -> bool { self == Self::ProRes @@ -544,7 +549,7 @@ pub struct HdrOutput { /// What the caller gets to decide about the output. The codec is not among it: /// [`Format`] names a container *and* what goes in it, because every pair we /// can write is a pair we can also read back. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq)] pub struct ExportSettings { /// Bits per second, clamped to the same sane range the automatic value uses. /// `None` picks it from the picture size and frame rate. Video only. @@ -687,6 +692,12 @@ pub struct ExportSettings { pub hevc_speed: Option, /// What a GIF asks for beyond the picture ([`Format::Gif`]); means nothing to any other format. pub gif: GifSettings, + /// Seconds between key frames of a video export's H.264, HEVC or AV1 picture, `None` for the + /// encoder's own. Refused with [`ExportSettings::intra_only`], which codes every picture a key frame. + pub keyframe_s: Option, + /// Lays an mp4 out `ftyp`, `moov`, `mdat` so it can start playing before its end. Means + /// something only to [`Format::Mp4`], [`Format::HevcMp4`], [`Format::Av1Mp4`] and [`Format::M4a`]. + pub faststart: bool, } /// The settings of an animated GIF ([`Format::Gif`]): its width in pixels (the height follows @@ -1262,6 +1273,11 @@ fn rate_of(meta: &VideoMeta, settings: &ExportSettings) -> SeatRate { } } +/// The pictures between key frames the caller asked for, `None` for the encoder's own. +fn gop_frames(meta: &VideoMeta, settings: &ExportSettings) -> Option { + settings.keyframe_s.map(|s| (meta.frame_rate * s).round().max(1.0) as u32) +} + /// The rate the sound codes at: the caller's pick clamped into the offered /// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused, /// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and @@ -1327,13 +1343,14 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option None, format if format.is_av1() => { - HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate) + HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings)) } // An intra-only H.264 file is a *different seat*, not the same seat with // a flag on the pictures: asking this one for a key frame every time @@ -1348,7 +1365,7 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, rate) } - _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate), + _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings)), } } @@ -5156,6 +5173,12 @@ fn run( if settings.intra_only && !matches!(settings.format, Format::Mp4 | Format::Hevc | Format::HevcMp4) { return Err(format!("{} cannot be written intra-only", settings.format.name()).into()); } + if settings.keyframe_s.is_some() && settings.intra_only { + return Err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one".into()); + } + if settings.faststart && !settings.format.is_mp4_family() { + return Err(format!("faststart lays out an mp4 file, and {} is not one", settings.format.name()).into()); + } if let Some(why) = exact_refusal(project, meta, settings) { return Err(why.into()); } @@ -6224,6 +6247,7 @@ fn run( for packet in track.into_iter().flat_map(|track| track.packets) { mp4.write_audio_packet(&packet.bytes)?; } + mp4.set_faststart(settings.faststart); mp4.set_chapters(&settings.chapters)?; mp4.write_subtitles(&subs)?; Muxer::Mp4(mp4) @@ -7606,6 +7630,7 @@ fn run_aac( .fetch_max((i * PROGRESS_SCALE as usize / count) as u32, Ordering::Relaxed); } cancelled(shared)?; + mp4.set_faststart(settings.faststart); mp4.set_chapters(&settings.chapters)?; mp4.finish()?; shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); @@ -8349,7 +8374,7 @@ impl Enc { // starting point ([`ExportSettings::intra_only`]). cfg.gop_size = match settings.intra_only { true => 1, - false => (meta.frame_rate * 2.0).round().max(1.0) as u32, + false => gop_frames(meta, settings).unwrap_or((meta.frame_rate * 2.0).round().max(1.0) as u32), }; // Fast, the rung a fallback is allowed to cost -- the cheaper arm of // the preset ladder, the one the old seat's own S1 also picked when its @@ -8400,7 +8425,7 @@ impl Enc { let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; // Two seconds between keyframes, as the H.264 seat does: a seek may only // land on one, and this is what a cluster of the Matroska file is. - let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; + let gop = gop_frames(meta, settings).map_or_else(|| (meta.frame_rate * 2.0).round().max(1.0) as u64, u64::from); // The 10-bit seat is software: the GPU encode is 8-bit only. let hw = match ten_bit { true => None, @@ -8920,6 +8945,9 @@ fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> { /// 256; a 60 fps export is 60 pictures and a faster one takes the serial path. const HEVC_GOP_MAX_KEYINT: usize = 64; +/// The longest key interval `ec-h265` codes, in pictures; a `keyframe_s` past it is capped here. +const HEVC_KEYINT_MAX: usize = 256; + impl Enc { /// The HEVC I+P seat: `ec-h265`'s sequence coder, an IDR once a second at /// the picture's own rate with P pictures between, on a worker thread. @@ -8941,7 +8969,7 @@ impl Enc { ten_bit: bool, colour: ColorDescription, ) -> crate::Result { - let keyint = hevc_gop_keyint(meta.frame_rate); + let keyint = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| (g as usize).clamp(2, HEVC_KEYINT_MAX)); let mut cfg = HevcEncoderConfig::new(meta.width, meta.height); cfg.bit_depth = if ten_bit { 10 } else { 8 }; cfg.rate_control = match (settings.qp, settings.bitrate) { @@ -9023,7 +9051,7 @@ pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option, + /// `Some` sets the seconds between key frames; `None` leaves the caller's. + pub keyframe_s: Option, + /// Whether the mp4 is laid out for streaming ([`ExportSettings::faststart`]). + pub faststart: bool, } const PODCAST: Option = Some(LoudnessTarget { lufs: -16.0, true_peak_dbtp: -1.0 }); @@ -94,6 +100,9 @@ const fn video( loudness: None, prores_profile: None, hdr: HdrTransfer::Sdr, + qp: None, + keyframe_s: None, + faststart: false, } } @@ -118,6 +127,9 @@ const fn sound( loudness, prores_profile: None, hdr: HdrTransfer::Sdr, + qp: None, + keyframe_s: None, + faststart: false, } } @@ -125,13 +137,29 @@ const WEB: Category = Category::Web; const HD: (u32, u32) = (1920, 1080); const UHD: (u32, u32) = (3840, 2160); -static TABLE: [Preset; 15] = [ +static TABLE: [Preset; 16] = [ video("youtube_1080p", "YouTube 1920×1080", "H.264 1080p30 at 8 Mb/s, AAC 384k: YouTube's recommended SDR upload.", WEB, Format::Mp4, 8, HD, 384), video("youtube_1080p60", "YouTube 1920×1080 60fps", "H.264 1080p60 at 12 Mb/s, AAC 384k.", WEB, Format::Mp4, 12, HD, 384), video("youtube_1080p_hevc", "YouTube 1920×1080 HEVC", "HEVC 1080p at 6 Mb/s in an mp4, AAC 384k: a smaller file at the same look.", WEB, Format::HevcMp4, 6, HD, 384), video("youtube_4k", "YouTube 3840×2160", "H.264 2160p30 at 40 Mb/s, AAC 384k.", WEB, Format::Mp4, 40, UHD, 384), video("youtube_4k60", "YouTube 3840×2160 60fps", "H.264 2160p60 at 50 Mb/s (the engine's ceiling; YouTube suggests 53-68), AAC 384k.", WEB, Format::Mp4, 50, UHD, 384), video("youtube_4k_hevc", "YouTube 3840×2160 HEVC", "HEVC 2160p at 28 Mb/s in an mp4, AAC 384k.", WEB, Format::HevcMp4, 28, UHD, 384), + Preset { + id: "youtube_4k_master", + label: "YouTube 3840×2160 master", + description: "HEVC 2160p, constant QP 18 on the GPU, 0.5 s keyframes, AAC 384k, faststart: an upload YouTube re-encodes from.", + target: Target { category: WEB, output: Output::Video, size: Some(UHD) }, + format: Format::HevcMp4, + bitrate: None, + audio_kbps: 384, + video_bit_depth: None, + loudness: None, + prores_profile: None, + hdr: HdrTransfer::Sdr, + qp: Some(18), + keyframe_s: Some(0.5), + faststart: true, + }, video("shorts_reels", "Shorts / Reels", "Vertical 9:16 1080x1920, H.264 at 8 Mb/s, AAC 192k.", Category::Social, Format::Mp4, 8, (1080, 1920), 192), sound("podcast", "Podcast m4a", "AAC 128k in an m4a, levelled to -16 LUFS with a -1 dBTP ceiling.", Category::Audio, Format::M4a, 128, PODCAST), sound("podcast_ogg", "Podcast ogg", "Vorbis in an ogg, -16 LUFS, -1 dBTP.", Category::Audio, Format::Ogg, 128, PODCAST), @@ -148,6 +176,9 @@ static TABLE: [Preset; 15] = [ loudness: None, prores_profile: None, hdr: HdrTransfer::Sdr, + qp: None, + keyframe_s: None, + faststart: false, }, Preset { id: "archive_prores", @@ -161,6 +192,9 @@ static TABLE: [Preset; 15] = [ loudness: None, prores_profile: Some(ProResProfile::Hq), hdr: HdrTransfer::Sdr, + qp: None, + keyframe_s: None, + faststart: false, }, Preset { id: "hdr10_hevc", @@ -174,6 +208,9 @@ static TABLE: [Preset; 15] = [ loudness: None, prores_profile: None, hdr: HdrTransfer::Pq, + qp: None, + keyframe_s: None, + faststart: false, }, sound("archive_flac", "Archive FLAC", "Lossless FLAC of the mix.", Category::Archive, Format::Flac, 320, None), sound("archive_wav", "Archive WAV", "16-bit PCM WAV of the mix.", Category::Archive, Format::Wav, 320, None), @@ -209,6 +246,9 @@ pub fn apply(preset: &Preset, base: ExportSettings) -> ExportSettings { loudness: preset.loudness, prores_profile: preset.prores_profile.unwrap_or(base.prores_profile), hdr: HdrOutput { transfer: preset.hdr, ..HdrOutput::default() }, + qp: preset.qp.or(base.qp), + keyframe_s: preset.keyframe_s.or(base.keyframe_s), + faststart: preset.faststart || base.faststart, ..base } } diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index c82640d..d796e11 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -495,7 +495,7 @@ impl HwEncoder { /// is unavailable -- no child binary, no driver, dimensions the driver /// refuses, *or a child that died opening any of it* -- and the caller falls /// back to the software encoder. - pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option { + pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option) -> Option { Self::seated( Seat::H264, width, @@ -504,6 +504,7 @@ impl HwEncoder { fps_den, rate, ColorDescription::default(), + gop, ) } @@ -521,13 +522,14 @@ impl HwEncoder { fps_den, rate, ColorDescription::default(), + None, ) } /// The same, coding AV1 instead. `None` on a child or a GPU with no AV1 /// encoder, and the caller's software AV1 encoder takes the export without /// saying anything about it. - pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option { + pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option) -> Option { Self::seated( Seat::Av1, width, @@ -536,6 +538,7 @@ impl HwEncoder { fps_den, rate, ColorDescription::default(), + gop, ) } @@ -549,8 +552,9 @@ impl HwEncoder { fps_den: u32, rate: SeatRate, colour: ColorDescription, + gop: Option, ) -> Option { - Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour) + Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop) } /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`] @@ -563,9 +567,10 @@ impl HwEncoder { rate: SeatRate, colour: ColorDescription, ) -> Option { - Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour) + Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None) } + #[allow(clippy::too_many_arguments)] fn seated( seat: Seat, width: u32, @@ -574,6 +579,7 @@ impl HwEncoder { fps_den: u32, rate: SeatRate, colour: ColorDescription, + gop: Option, ) -> Option { let open = Open { seat, @@ -583,6 +589,7 @@ impl HwEncoder { fps_den, rate, colour, + gop, }; // No child binary beside the executable means no hardware seat at all: // `Remote::spawn` answers `None` before a process is forked. diff --git a/crates/engine/src/hwproc.rs b/crates/engine/src/hwproc.rs index c611906..37041d3 100644 --- a/crates/engine/src/hwproc.rs +++ b/crates/engine/src/hwproc.rs @@ -135,6 +135,8 @@ pub struct Open { /// What the sequence header will say the samples mean. Only the HEVC seat /// takes one; the others ignore it. pub colour: ColorDescription, + /// Pictures between key frames; `None` is the seat's own two seconds. + pub gop: Option, } impl Open { @@ -167,6 +169,7 @@ impl Open { SeatRate::Bitrate(bps) => [0, bps], SeatRate::ConstantQp(qp) => [1, u64::from(qp)], }.map(|v| v.to_string())) + .chain(std::iter::once(self.gop.unwrap_or(0).to_string())) .collect() } @@ -200,6 +203,10 @@ impl Open { }, full_range: n(7)? != 0, }, + gop: match n(10)? { + 0 => None, + gop => Some(gop), + }, }) } @@ -810,9 +817,11 @@ mod tests { transfer: Transfer::Pq, full_range: true, }, + gop: Some(15), }; let back = Open::from_argv(&open.argv()).expect("parse"); assert!(back.seat == Seat::Hevc); + assert_eq!(back.gop, Some(15)); assert_eq!( (back.width, back.height, back.fps_num, back.fps_den), (1920, 1080, 30000, 1001) diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 74ee8e2..b0ea168 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -13,7 +13,7 @@ use std::collections::VecDeque; use std::fs::File; -use std::io::{BufWriter, Seek, SeekFrom, Write}; +use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; use std::path::Path; use ec_core::{ @@ -121,11 +121,44 @@ const AUDIO_STREAM: u32 = 1; /// the sound from timeline frame 0 and does not run it 21 ms late. const AAC_PRIMING: u32 = 1024; +/// The file an mp4 is written to: buffered, and readable back for a faststart file. +struct Out(BufWriter); + +impl Out { + fn create(path: &Path) -> std::io::Result { + let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(path)?; + Ok(Self(BufWriter::new(file))) + } +} + +impl Write for Out { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.write(buf) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.0.flush() + } +} + +impl Read for Out { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.0.flush()?; + self.0.get_mut().read(buf) + } +} + +impl Seek for Out { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.0.seek(pos) + } +} + /// Writes one H.264, HEVC or AV1 track plus an optional AAC track, through /// `ec-mp4`'s muxer. Timing is carried per sample: every sample is handed over /// with its exact decode time and duration, so the tracks cannot drift. pub struct Mp4Muxer { - writer: ec_mp4::Mp4Muxer>, + writer: ec_mp4::Mp4Muxer, frame_duration: u32, /// Whether the file carries a picture track. A sound-only file /// ([`Mp4Muxer::create_audio_only`]) has none, and then the audio is the @@ -184,6 +217,8 @@ pub struct Mp4Muxer { /// The sound's exact length in PCM frames, where the caller knows it /// ([`Mp4Muxer::set_audio_frames`]). Only an audio-only file reads it. audio_frames: Option, + /// Whether the file is laid out for streaming ([`Mp4Muxer::set_faststart`]). + faststart: bool, } /// The H.273 colour description of a picture, as the `colr` box states it. @@ -254,6 +289,13 @@ fn mp4_language(language: &str) -> String { impl Mp4Muxer { + /// Lays the file out `ftyp`, `moov`, `mdat` so a player can start before the end. Set it before + /// [`finish`](Mp4Muxer::finish), which then reads the `mdat` back to move it. + pub fn set_faststart(&mut self, on: bool) { + self.faststart = on; + self.writer.set_faststart(on); + } + /// Declares the sound's exact length in PCM frames per channel, for an /// audio-only file: its `elst` plays `frames` samples from the priming and /// stops there, so the file says what was exported and not what the last @@ -274,7 +316,7 @@ impl Mp4Muxer { false => (*b"isom", &[*b"isom", *b"iso2", *b"mp41"]), }; let writer = ec_mp4::Mp4Muxer::with_brands( - BufWriter::new(File::create(path)?), + Out::create(path)?, major, compatible, ) @@ -297,6 +339,7 @@ impl Mp4Muxer { flushed_video_ticks: 0, audio_rate: 0, audio_frames: None, + faststart: false, }; muxer.add_audio_track(audio)?; Ok(muxer) @@ -381,7 +424,7 @@ impl Mp4Muxer { } let (timescale, frame_duration) = frame_timing(frame_rate)?; - let mut writer = ec_mp4::Mp4Muxer::new(BufWriter::new(File::create(path)?)) + let mut writer = ec_mp4::Mp4Muxer::new(Out::create(path)?) .map_err(mp4_error)?; let video_info = StreamInfo::new( VIDEO_STREAM, @@ -422,6 +465,7 @@ impl Mp4Muxer { flushed_video_ticks: 0, audio_rate: 0, audio_frames: None, + faststart: false, }; if let Some(audio) = audio { muxer.add_audio_track(audio)?; @@ -767,10 +811,15 @@ impl Mp4Muxer { .map_err(mp4_error)?; } } + let faststart = self.faststart; let mut writer = self.writer; - ec_core::Muxer::finish(&mut writer).map_err(mp4_error)?; - // Not a `drop`: a `BufWriter` swallows the error of flushing on drop. - writer.into_inner().flush()?; + if faststart { + writer.finish_faststart().map_err(mp4_error)?.0.flush()?; + } else { + ec_core::Muxer::finish(&mut writer).map_err(mp4_error)?; + // Not a `drop`: a `BufWriter` swallows the error of flushing on drop. + writer.into_inner().0.flush()?; + } Ok(()) } } diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 7bb4cc9..4eee8fd 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -772,7 +772,7 @@ fn exports_audio_alongside_the_video() { fn hardware_access_units_repack_into_mp4() { let (w, h) = (640u32, 480u32); let mut encoder = - HwEncoder::open(w, h, 30, 1, SeatRate::Bitrate(4_000_000)).expect("no hardware encode plugin/driver"); + HwEncoder::open(w, h, 30, 1, SeatRate::Bitrate(4_000_000), None).expect("no hardware encode plugin/driver"); let out = out_path("hwmux"); let mut muxer: Option = None; let mut written = 0; @@ -1919,7 +1919,7 @@ fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() { // No `VE_HW_TIMEOUT_MS` at all: the wait is the one a person's export gets. injected_with(None, Some("10"), None, || { let mut encoder = - HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000)).expect("the stand-in seat opened"); + HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000), None).expect("the stand-in seat opened"); let (y, u, v) = synthetic(0, width as usize, height as usize); for frame in 0..10 { assert!( @@ -2058,7 +2058,7 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() { let (width, height) = (320u32, 240u32); injected(Some("1"), None, || { let mut encoder = - HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000)).expect("the stand-in seat opened"); + HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000), None).expect("the stand-in seat opened"); let (y, u, v) = synthetic(0, width as usize, height as usize); assert!( encoder.encode(&y, &u, &v, width, height, false).is_ok(), diff --git a/crates/engine/tests/hw_encode.rs b/crates/engine/tests/hw_encode.rs index 6a9e2b5..4261d8d 100644 --- a/crates/engine/tests/hw_encode.rs +++ b/crates/engine/tests/hw_encode.rs @@ -45,7 +45,7 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec< /// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus /// the number of access units the plugin handed back. fn encode(width: u32, height: u32, count: u32) -> Option<(Vec, u32)> { - let mut encoder = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE))?; + let mut encoder = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE), None)?; let mut stream = Vec::new(); let mut units = 0; // Timed around the plugin call only: building the synthetic picture is not @@ -249,7 +249,7 @@ fn a_decoded_buffer_is_encoded_without_ever_being_read_back() { let asset = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4"); let (width, height) = (1280u32, 720u32); - let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE)) else { + let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE), None) else { println!("no hardware encoder here -- skipping"); return; }; @@ -367,13 +367,13 @@ fn decode_and_encode_load_independently() { let asset = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4"); assert!( - HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE)).is_some(), + HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE), None).is_some(), "encode table" ); assert!(HwSession::open(&asset).is_some(), "decode table"); // Order reversed: neither table's `OnceLock` may have primed the other. assert!(HwSession::open(&asset).is_some()); - assert!(HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE)).is_some()); + assert!(HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE), None).is_some()); } /// Per slice: `(is_idr, frame_num, pic_order_cnt_lsb)`, read by [`slice_counters`]. diff --git a/crates/mcp/src/help.rs b/crates/mcp/src/help.rs index 654d71c..cfc1d6f 100644 --- a/crates/mcp/src/help.rs +++ b/crates/mcp/src/help.rs @@ -226,7 +226,7 @@ LANES const EXPORT: &str = "\ EXPORT - export_start {out, preset?, loudness?, format?, range?, size?, fit?, bitrate_kbps?, qp?, audio_kbps?, bit_depth?, prores_profile?, hevc_speed?, hdr?, audio_bit_depth?, chapters?, intra_only?, seat?, subtitles?, burn_captions?, overwrite?} + export_start {out, preset?, loudness?, format?, range?, size?, fit?, bitrate_kbps?, qp?, keyframe_s?, faststart?, audio_kbps?, bit_depth?, prores_profile?, hevc_speed?, hdr?, audio_bit_depth?, chapters?, intra_only?, seat?, subtitles?, burn_captions?, overwrite?} returns job: at once. Poll it with export_status {job?}; export_cancel {job} stops it and deletes the partial file. out: the file to write; ~/ is expanded and its folder must exist. The extension picks the format: .mp4 mp4 · .mkv av1 · .webm · .wav · .flac · .mp3 · .ogg · .m4a · .opus · .mov prores. Refuses an existing file unless overwrite:true. @@ -240,7 +240,7 @@ EXPORT size: this export's picture size, WIDTHxHEIGHT (1280x720) or a height with p (720p, 1080p, 2160p, 16:9 at that height); 1080x1920 is vertical. Both sides even. Omitted: the project's resolution, which stays as it is. fit: how every picture clip meets this export's canvas: keep (the default: each clip's own fit), fit (whole picture, bars) or fill (the canvas covered, the picture cropped). It changes this export's copy only; the project's clips keep their fit. Captions and titles keep their place on the canvas. A 16:9 timeline as 9:16: export_start {out, size:\"1080x1920\", fit:\"fill\"}. The reply names the size and the fit, and the clip count they applied to. - bitrate_kbps: video, chosen from the picture size and frame rate when omitted. qp: a constant quantiser 0..51 instead of a bitrate (not with bitrate_kbps): the hardware seat for H.264, HEVC and AV1, and the software HEVC encoder; the software H.264 and AV1 encoders refuse it. audio_kbps: 128, 192, 256 or 320, and 384 for AAC only. + bitrate_kbps: video, chosen from the picture size and frame rate when omitted. qp: a constant quantiser 0..51 instead of a bitrate (not with bitrate_kbps): the hardware seat for H.264, HEVC and AV1, and the software HEVC encoder; the software H.264 and AV1 encoders refuse it. keyframe_s: seconds between key frames, 0.1 to 10 (not with intra_only). faststart: mp4, hevc-mp4, av1-mp4 and m4a only, moov before mdat so it plays before it is fully read. audio_kbps: 128, 192, 256 or 320, and 384 for AAC only. intra_only: hevc and hevc-mp4: true codes every picture as an IDR (intra only, large files, every frame a cut point). false, the default, codes I+P GOPs (an IDR a second, P pictures between). h264 mp4 uses it the same way. Captions: burn_captions draws one track into the picture, so every player and WebM show it. subtitles adds soft tracks a player can switch off (WebM has none). Both together: burned and soft. burn_captions alone: no soft track. diff --git a/crates/mcp/src/tools/export.rs b/crates/mcp/src/tools/export.rs index 8b9758d..b3bd18b 100644 --- a/crates/mcp/src/tools/export.rs +++ b/crates/mcp/src/tools/export.rs @@ -36,7 +36,7 @@ pub fn tools() -> Vec { }, Tool { name: "export_presets", - description: "List the export presets export_start { preset: \"\" } takes: id, label and the settings each sets (format, bitrate_kbps, audio_kbps, size, bit_depth, loudness). Explicit export_start arguments override the preset.", + description: "List the export presets export_start { preset: \"\" } takes: id, label and the settings each sets (format, bitrate_kbps, audio_kbps, size, bit_depth, qp, keyframe_s, faststart, loudness). Explicit export_start arguments override the preset.", schema: presets_schema, run: export_presets, }, @@ -168,6 +168,9 @@ fn preset_json(p: &engine::export_presets::Preset) -> Value { "audio_kbps": p.audio_kbps, "size": p.target.size.map(|(w, h)| format!("{w}x{h}")), "bit_depth": p.video_bit_depth, + "qp": p.qp, + "keyframe_s": p.keyframe_s, + "faststart": p.faststart, "prores_profile": p.prores_profile.map(prores_name), "hdr": hdr_name(p.hdr), "loudness": p.loudness.map(|l| json!({ "lufs": l.lufs, "true_peak_dbtp": l.true_peak_dbtp })), @@ -259,7 +262,7 @@ fn start_schema() -> Value { "preset": { "type": "string", "enum": engine::export_presets::presets().iter().map(|p| p.id).collect::>(), - "description": "An export preset id (list them with export_presets): fills format, bitrate_kbps, audio_kbps, size, bit_depth and, for sound, a loudness target. Anything else you pass overrides the preset's value; `out`'s extension must match the preset's format." + "description": "An export preset id (list them with export_presets): fills format, bitrate_kbps, audio_kbps, size, bit_depth, qp, keyframe_s, faststart and, for sound, a loudness target. Anything else you pass overrides the preset's value; `out`'s extension must match the preset's format." }, "loudness": { "type": "number", @@ -320,6 +323,16 @@ fn start_schema() -> Value { "maximum": 51, "description": "Constant quantiser for the picture instead of a bitrate, 0 (best, largest) to 51. The hardware seat codes at it for H.264, HEVC and AV1 (AV1 scaled to its 0..255), and the software HEVC encoder too; the software H.264 and AV1 encoders refuse it. Video formats only (mp4, av1, av1-mp4, hevc, hevc-mp4, webm). Not with bitrate_kbps." }, + "keyframe_s": { + "type": "number", + "minimum": 0.1, + "maximum": 10, + "description": "Seconds between key frames of the picture (H.264, HEVC, AV1), instead of the encoder's own two. Rounded to whole pictures at the frame rate. Not with intra_only or a sound-only export. Software HEVC caps it at 256 pictures." + }, + "faststart": { + "type": "boolean", + "description": "Lay an mp4 out so a player can start before the file is fully read (moov before mdat). Only mp4, hevc-mp4, av1-mp4 and m4a; refused for other formats. Default false, or the preset's." + }, "audio_kbps": { "type": "integer", "enum": [128, 192, 256, 320, 384], @@ -1541,8 +1554,9 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply { Some(k) => Some(k.saturating_mul(1000)), None => None, }; + let intra_only = opt_bool(args, "intra_only").unwrap_or(false); let qp = match opt_u64(args, "qp") { - None => None, + None => preset.and_then(|p| p.qp).filter(|_| bitrate.is_none() && !sound_only), Some(q) if q <= 51 => Some(q as u32), Some(q) => return Reply::err(format!("qp {q} is not 0 to 51")), }; @@ -1564,6 +1578,26 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply { if qp.is_some() && seat == EncoderSeat::Software && !format.is_hevc() { return Reply::err("qp with seat software: only the software HEVC encoder writes a constant QP; use seat auto or hardware for H.264"); } + let keyframe_s = match args.get("keyframe_s") { + None | Some(Value::Null) => preset.and_then(|p| p.keyframe_s).filter(|_| !intra_only && !sound_only), + Some(v) => match v.as_f64() { + Some(secs) if (0.1..=10.0).contains(&secs) => Some(secs), + _ => return Reply::err("keyframe_s is a number of seconds, from 0.1 to 10"), + }, + }; + if keyframe_s.is_some() && intra_only { + return Reply::err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one"); + } + if keyframe_s.is_some() && sound_only { + return Reply::err("keyframe_s sets the picture's key frames, and this export is the sound alone"); + } + let faststart = opt_bool(args, "faststart").unwrap_or(preset.is_some_and(|p| p.faststart)); + if faststart && !format.is_mp4_family() { + return Reply::err(format!( + "faststart lays out an mp4, and {} is not one: use mp4, hevc-mp4, av1-mp4 or m4a", + format_name(format) + )); + } let audio_kbps = match opt_u64(args, "audio_kbps") { None => None, Some(k) => { @@ -1725,7 +1759,9 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply { qp, seat, format, - intra_only: opt_bool(args, "intra_only").unwrap_or(false), + intra_only, + keyframe_s, + faststart, audio_kbps, subtitles, no_soft_subtitles: no_soft,