forge
Explore
Log in

Don't you dare go Hollow

✨ export_start takes keyframe_s and faststart, and a youtube_4k_master preset writes HEVC at constant QP 18 on the GPU with 0.5 s keyframes, AAC 384k and the moov in front

Browse files at this commit

c549c12854c0aa022cfd9237712a0fad022c11c3Ahmet Kaan GümüşParent: 53251aa
MCP.mdmodified+1 -1
@@ -406,7 +406,7 @@ Piper's stderr is reported on failure.
406 406
407 | tool | args | does |407 | tool | args | does |
408 |---|---|---|408 |---|---|---|
409-| `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:<n>` 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) |409+| `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:<n>` 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) |
410 | `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 |410 | `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 |
411 | `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`: `<first source> edit.<format>` 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`) |411 | `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`: `<first source> edit.<format>` 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`) |
412 | `proxies` | action (`status`, the default, `make`, `cancel` or `delete`), source (`src:<n>`, 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 |412 | `proxies` | action (`status`, the default, `make`, `cancel` or `delete`), source (`src:<n>`, 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 |
crates/app/src/export_ui.rsmodified+2 -0
@@ -774,6 +774,8 @@ pub(crate) fn export_settings(
774 hdr: HdrOutput::default(),774 hdr: HdrOutput::default(),
775 hevc_speed: None,775 hevc_speed: None,
776 gif: GifSettings::default(),776 gif: GifSettings::default(),
777+ keyframe_s: None,
778+ faststart: false,
777 }779 }
778 }780 }
779 781
crates/engine-hw/src/enc_ec.rsmodified+7 -1
@@ -48,6 +48,8 @@ pub(crate) struct EcOpen {
48 pub rate: SeatRate,48 pub rate: SeatRate,
49 /// Every picture an IDR: what a proxy is coded with (see `gop_limit`).49 /// Every picture an IDR: what a proxy is coded with (see `gop_limit`).
50 pub intra_only: bool,50 pub intra_only: bool,
51+ /// Pictures between key frames; `None` is `gop_limit`'s.
52+ pub gop: Option<u32>,
51 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.53 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.
52 pub colour: Option<(u8, u8, u8, bool)>,54 pub colour: Option<(u8, u8, u8, bool)>,
53 }55 }
@@ -62,6 +64,7 @@ impl EcEncSession {
62 fps_den,64 fps_den,
63 rate,65 rate,
64 intra_only,66 intra_only,
67+ gop,
65 colour,68 colour,
66 } = req;69 } = req;
67 // NV12 chroma is half resolution, so odd dimensions have no packing;70 // NV12 chroma is half resolution, so odd dimensions have no packing;
@@ -84,7 +87,10 @@ impl EcEncSession {
84 if let SeatRate::Bitrate(bitrate) = rate {87 if let SeatRate::Bitrate(bitrate) = rate {
85 config.bitrate = u32::try_from(bitrate).unwrap_or(u32::MAX);88 config.bitrate = u32::try_from(bitrate).unwrap_or(u32::MAX);
86 }89 }
87- config.gop_size = u32::from(crate::gop_limit(framerate, intra_only));90+ config.gop_size = gop.unwrap_or_else(|| match (codec, intra_only) {
91+ (EncCodec::H265, false) => framerate,
92+ _ => u32::from(crate::gop_limit(framerate, intra_only)),
93+ });
88 config.rate_control = match (codec, rate) {94 config.rate_control = match (codec, rate) {
89 (EncCodec::Av1, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp: qp.min(51) * 255 / 51 },95 (EncCodec::Av1, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp: qp.min(51) * 255 / 51 },
90 (_, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp },96 (_, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp },
crates/engine-hw/src/lib.rsmodified+3 -0
@@ -820,6 +820,7 @@ pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option<EcEncSession>
820 fps_den: open.fps_den,820 fps_den: open.fps_den,
821 rate: open.rate,821 rate: open.rate,
822 intra_only,822 intra_only,
823+ gop: open.gop,
823 colour,824 colour,
824 })825 })
825 }826 }
@@ -868,6 +869,7 @@ mod tests {
868 fps_den: 1,869 fps_den: 1,
869 rate: SeatRate::Bitrate(2_000_000),870 rate: SeatRate::Bitrate(2_000_000),
870 intra_only: true,871 intra_only: true,
872+ gop: None,
871 colour: None,873 colour: None,
872 };874 };
873 // No VA-API on this machine: nothing to encode, nothing to claim.875 // No VA-API on this machine: nothing to encode, nothing to claim.
@@ -949,6 +951,7 @@ mod tests {
949 fps_den: 1,951 fps_den: 1,
950 rate: SeatRate::Bitrate(2_000_000),952 rate: SeatRate::Bitrate(2_000_000),
951 intra_only: true,953 intra_only: true,
954+ gop: None,
952 colour: None,955 colour: None,
953 };956 };
954 let Some(mut session) = EcEncSession::open(open) else {957 let Some(mut session) = EcEncSession::open(open) else {
crates/engine/src/export.rsmodified+35 -7
@@ -328,6 +328,11 @@ impl Format {
328 matches!(self, Self::Hevc | Self::HevcMp4)328 matches!(self, Self::Hevc | Self::HevcMp4)
329 }329 }
330 330
331+ /// Whether the file is an mp4 box file (mp4, hevc-mp4, av1-mp4 or m4a), which is what faststart lays out.
332+ pub fn is_mp4_family(self) -> bool {
333+ matches!(self, Self::Mp4 | Self::HevcMp4 | Self::Av1Mp4 | Self::M4a)
334+ }
335+
331 /// Whether the picture is ProRes in a QuickTime file ([`Format::ProRes`]).336 /// Whether the picture is ProRes in a QuickTime file ([`Format::ProRes`]).
332 pub fn is_prores(self) -> bool {337 pub fn is_prores(self) -> bool {
333 self == Self::ProRes338 self == Self::ProRes
@@ -544,7 +549,7 @@ pub struct HdrOutput {
544 /// What the caller gets to decide about the output. The codec is not among it:549 /// What the caller gets to decide about the output. The codec is not among it:
545 /// [`Format`] names a container *and* what goes in it, because every pair we550 /// [`Format`] names a container *and* what goes in it, because every pair we
546 /// can write is a pair we can also read back.551 /// can write is a pair we can also read back.
547-#[derive(Debug, Clone, Default, PartialEq, Eq)]552+#[derive(Debug, Clone, Default, PartialEq)]
548 pub struct ExportSettings {553 pub struct ExportSettings {
549 /// Bits per second, clamped to the same sane range the automatic value uses.554 /// Bits per second, clamped to the same sane range the automatic value uses.
550 /// `None` picks it from the picture size and frame rate. Video only.555 /// `None` picks it from the picture size and frame rate. Video only.
@@ -687,6 +692,12 @@ pub struct ExportSettings {
687 pub hevc_speed: Option<HevcSpeed>,692 pub hevc_speed: Option<HevcSpeed>,
688 /// What a GIF asks for beyond the picture ([`Format::Gif`]); means nothing to any other format.693 /// What a GIF asks for beyond the picture ([`Format::Gif`]); means nothing to any other format.
689 pub gif: GifSettings,694 pub gif: GifSettings,
695+ /// Seconds between key frames of a video export's H.264, HEVC or AV1 picture, `None` for the
696+ /// encoder's own. Refused with [`ExportSettings::intra_only`], which codes every picture a key frame.
697+ pub keyframe_s: Option<f64>,
698+ /// Lays an mp4 out `ftyp`, `moov`, `mdat` so it can start playing before its end. Means
699+ /// something only to [`Format::Mp4`], [`Format::HevcMp4`], [`Format::Av1Mp4`] and [`Format::M4a`].
700+ pub faststart: bool,
690 }701 }
691 702
692 /// The settings of an animated GIF ([`Format::Gif`]): its width in pixels (the height follows703 /// 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 {
1262 }1273 }
1263 }1274 }
1264 1275
1276+/// The pictures between key frames the caller asked for, `None` for the encoder's own.
1277+fn gop_frames(meta: &VideoMeta, settings: &ExportSettings) -> Option<u32> {
1278+ settings.keyframe_s.map(|s| (meta.frame_rate * s).round().max(1.0) as u32)
1279+}
1280+
1265 /// The rate the sound codes at: the caller's pick clamped into the offered1281 /// The rate the sound codes at: the caller's pick clamped into the offered
1266 /// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,1282 /// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,
1267 /// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and1283 /// 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<HwEncoder
1327 fps_den,1343 fps_den,
1328 rate,1344 rate,
1329 ColorDescription::output_sized(meta.width, meta.height),1345 ColorDescription::output_sized(meta.width, meta.height),
1346+ gop_frames(meta, settings),
1330 ),1347 ),
1331 // Asked for by name only, for the reason [`Enc::open_av1`] states in1348 // Asked for by name only, for the reason [`Enc::open_av1`] states in
1332 // full: `Auto` takes the software encoder here and nowhere else. Both1349 // full: `Auto` takes the software encoder here and nowhere else. Both
1333 // AV1 formats sit on it: the container is not the encoder's business.1350 // AV1 formats sit on it: the container is not the encoder's business.
1334 format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None,1351 format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None,
1335 format if format.is_av1() => {1352 format if format.is_av1() => {
1336- HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate)1353+ HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings))
1337 }1354 }
1338 // An intra-only H.264 file is a *different seat*, not the same seat with1355 // An intra-only H.264 file is a *different seat*, not the same seat with
1339 // a flag on the pictures: asking this one for a key frame every time1356 // 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
1348 _ if settings.intra_only => {1365 _ if settings.intra_only => {
1349 HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, rate)1366 HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, rate)
1350 }1367 }
1351- _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate),1368+ _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings)),
1352 }1369 }
1353 }1370 }
1354 1371
@@ -5156,6 +5173,12 @@ fn run(
5156 if settings.intra_only && !matches!(settings.format, Format::Mp4 | Format::Hevc | Format::HevcMp4) {5173 if settings.intra_only && !matches!(settings.format, Format::Mp4 | Format::Hevc | Format::HevcMp4) {
5157 return Err(format!("{} cannot be written intra-only", settings.format.name()).into());5174 return Err(format!("{} cannot be written intra-only", settings.format.name()).into());
5158 }5175 }
5176+ if settings.keyframe_s.is_some() && settings.intra_only {
5177+ return Err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one".into());
5178+ }
5179+ if settings.faststart && !settings.format.is_mp4_family() {
5180+ return Err(format!("faststart lays out an mp4 file, and {} is not one", settings.format.name()).into());
5181+ }
5159 if let Some(why) = exact_refusal(project, meta, settings) {5182 if let Some(why) = exact_refusal(project, meta, settings) {
5160 return Err(why.into());5183 return Err(why.into());
5161 }5184 }
@@ -6224,6 +6247,7 @@ fn run(
6224 for packet in track.into_iter().flat_map(|track| track.packets) {6247 for packet in track.into_iter().flat_map(|track| track.packets) {
6225 mp4.write_audio_packet(&packet.bytes)?;6248 mp4.write_audio_packet(&packet.bytes)?;
6226 }6249 }
6250+ mp4.set_faststart(settings.faststart);
6227 mp4.set_chapters(&settings.chapters)?;6251 mp4.set_chapters(&settings.chapters)?;
6228 mp4.write_subtitles(&subs)?;6252 mp4.write_subtitles(&subs)?;
6229 Muxer::Mp4(mp4)6253 Muxer::Mp4(mp4)
@@ -7606,6 +7630,7 @@ fn run_aac(
7606 .fetch_max((i * PROGRESS_SCALE as usize / count) as u32, Ordering::Relaxed);7630 .fetch_max((i * PROGRESS_SCALE as usize / count) as u32, Ordering::Relaxed);
7607 }7631 }
7608 cancelled(shared)?;7632 cancelled(shared)?;
7633+ mp4.set_faststart(settings.faststart);
7609 mp4.set_chapters(&settings.chapters)?;7634 mp4.set_chapters(&settings.chapters)?;
7610 mp4.finish()?;7635 mp4.finish()?;
7611 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);7636 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
@@ -8349,7 +8374,7 @@ impl Enc {
8349 // starting point ([`ExportSettings::intra_only`]).8374 // starting point ([`ExportSettings::intra_only`]).
8350 cfg.gop_size = match settings.intra_only {8375 cfg.gop_size = match settings.intra_only {
8351 true => 1,8376 true => 1,
8352- false => (meta.frame_rate * 2.0).round().max(1.0) as u32,8377+ false => gop_frames(meta, settings).unwrap_or((meta.frame_rate * 2.0).round().max(1.0) as u32),
8353 };8378 };
8354 // Fast, the rung a fallback is allowed to cost -- the cheaper arm of8379 // Fast, the rung a fallback is allowed to cost -- the cheaper arm of
8355 // the preset ladder, the one the old seat's own S1 also picked when its8380 // the preset ladder, the one the old seat's own S1 also picked when its
@@ -8400,7 +8425,7 @@ impl Enc {
8400 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;8425 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
8401 // Two seconds between keyframes, as the H.264 seat does: a seek may only8426 // Two seconds between keyframes, as the H.264 seat does: a seek may only
8402 // land on one, and this is what a cluster of the Matroska file is.8427 // land on one, and this is what a cluster of the Matroska file is.
8403- let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;8428+ let gop = gop_frames(meta, settings).map_or_else(|| (meta.frame_rate * 2.0).round().max(1.0) as u64, u64::from);
8404 // The 10-bit seat is software: the GPU encode is 8-bit only.8429 // The 10-bit seat is software: the GPU encode is 8-bit only.
8405 let hw = match ten_bit {8430 let hw = match ten_bit {
8406 true => None,8431 true => None,
@@ -8920,6 +8945,9 @@ fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {
8920 /// 256; a 60 fps export is 60 pictures and a faster one takes the serial path.8945 /// 256; a 60 fps export is 60 pictures and a faster one takes the serial path.
8921 const HEVC_GOP_MAX_KEYINT: usize = 64;8946 const HEVC_GOP_MAX_KEYINT: usize = 64;
8922 8947
8948+/// The longest key interval `ec-h265` codes, in pictures; a `keyframe_s` past it is capped here.
8949+const HEVC_KEYINT_MAX: usize = 256;
8950+
8923 impl Enc {8951 impl Enc {
8924 /// The HEVC I+P seat: `ec-h265`'s sequence coder, an IDR once a second at8952 /// The HEVC I+P seat: `ec-h265`'s sequence coder, an IDR once a second at
8925 /// the picture's own rate with P pictures between, on a worker thread.8953 /// the picture's own rate with P pictures between, on a worker thread.
@@ -8941,7 +8969,7 @@ impl Enc {
8941 ten_bit: bool,8969 ten_bit: bool,
8942 colour: ColorDescription,8970 colour: ColorDescription,
8943 ) -> crate::Result<Self> {8971 ) -> crate::Result<Self> {
8944- let keyint = hevc_gop_keyint(meta.frame_rate);8972+ let keyint = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| (g as usize).clamp(2, HEVC_KEYINT_MAX));
8945 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);8973 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);
8946 cfg.bit_depth = if ten_bit { 10 } else { 8 };8974 cfg.bit_depth = if ten_bit { 10 } else { 8 };
8947 cfg.rate_control = match (settings.qp, settings.bitrate) {8975 cfg.rate_control = match (settings.qp, settings.bitrate) {
@@ -9023,7 +9051,7 @@ pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<St
9023 ),9051 ),
9024 });9052 });
9025 }9053 }
9026- let seconds = hevc_gop_keyint(meta.frame_rate) as f64 / meta.frame_rate;9054+ let seconds = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| g as usize) as f64 / meta.frame_rate;
9027 let every = if (seconds - seconds.round()).abs() < 1e-6 {9055 let every = if (seconds - seconds.round()).abs() < 1e-6 {
9028 format!("{} s", seconds.round() as u64)9056 format!("{} s", seconds.round() as u64)
9029 } else {9057 } else {
crates/engine/src/export_presets.rsmodified+41 -1
@@ -67,6 +67,12 @@ pub struct Preset {
67 /// The HDR transfer of an HEVC file; [`HdrTransfer::Sdr`] is none, and [`apply`] clears any67 /// The HDR transfer of an HEVC file; [`HdrTransfer::Sdr`] is none, and [`apply`] clears any
68 /// the caller had, since an HDR tag on another preset's file would be refused.68 /// the caller had, since an HDR tag on another preset's file would be refused.
69 pub hdr: HdrTransfer,69 pub hdr: HdrTransfer,
70+ /// `Some` sets a constant quantiser for the picture; `None` leaves the caller's.
71+ pub qp: Option<u32>,
72+ /// `Some` sets the seconds between key frames; `None` leaves the caller's.
73+ pub keyframe_s: Option<f64>,
74+ /// Whether the mp4 is laid out for streaming ([`ExportSettings::faststart`]).
75+ pub faststart: bool,
70 }76 }
71 77
72 const PODCAST: Option<LoudnessTarget> = Some(LoudnessTarget { lufs: -16.0, true_peak_dbtp: -1.0 });78 const PODCAST: Option<LoudnessTarget> = Some(LoudnessTarget { lufs: -16.0, true_peak_dbtp: -1.0 });
@@ -94,6 +100,9 @@ const fn video(
94 loudness: None,100 loudness: None,
95 prores_profile: None,101 prores_profile: None,
96 hdr: HdrTransfer::Sdr,102 hdr: HdrTransfer::Sdr,
103+ qp: None,
104+ keyframe_s: None,
105+ faststart: false,
97 }106 }
98 }107 }
99 108
@@ -118,6 +127,9 @@ const fn sound(
118 loudness,127 loudness,
119 prores_profile: None,128 prores_profile: None,
120 hdr: HdrTransfer::Sdr,129 hdr: HdrTransfer::Sdr,
130+ qp: None,
131+ keyframe_s: None,
132+ faststart: false,
121 }133 }
122 }134 }
123 135
@@ -125,13 +137,29 @@ const WEB: Category = Category::Web;
125 const HD: (u32, u32) = (1920, 1080);137 const HD: (u32, u32) = (1920, 1080);
126 const UHD: (u32, u32) = (3840, 2160);138 const UHD: (u32, u32) = (3840, 2160);
127 139
128-static TABLE: [Preset; 15] = [140+static TABLE: [Preset; 16] = [
129 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),141 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),
130 video("youtube_1080p60", "YouTube 1920×1080 60fps", "H.264 1080p60 at 12 Mb/s, AAC 384k.", WEB, Format::Mp4, 12, HD, 384),142 video("youtube_1080p60", "YouTube 1920×1080 60fps", "H.264 1080p60 at 12 Mb/s, AAC 384k.", WEB, Format::Mp4, 12, HD, 384),
131 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),143 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),
132 video("youtube_4k", "YouTube 3840×2160", "H.264 2160p30 at 40 Mb/s, AAC 384k.", WEB, Format::Mp4, 40, UHD, 384),144 video("youtube_4k", "YouTube 3840×2160", "H.264 2160p30 at 40 Mb/s, AAC 384k.", WEB, Format::Mp4, 40, UHD, 384),
133 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),145 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),
134 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),146 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),
147+ Preset {
148+ id: "youtube_4k_master",
149+ label: "YouTube 3840×2160 master",
150+ description: "HEVC 2160p, constant QP 18 on the GPU, 0.5 s keyframes, AAC 384k, faststart: an upload YouTube re-encodes from.",
151+ target: Target { category: WEB, output: Output::Video, size: Some(UHD) },
152+ format: Format::HevcMp4,
153+ bitrate: None,
154+ audio_kbps: 384,
155+ video_bit_depth: None,
156+ loudness: None,
157+ prores_profile: None,
158+ hdr: HdrTransfer::Sdr,
159+ qp: Some(18),
160+ keyframe_s: Some(0.5),
161+ faststart: true,
162+ },
135 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),163 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),
136 sound("podcast", "Podcast m4a", "AAC 128k in an m4a, levelled to -16 LUFS with a -1 dBTP ceiling.", Category::Audio, Format::M4a, 128, PODCAST),164 sound("podcast", "Podcast m4a", "AAC 128k in an m4a, levelled to -16 LUFS with a -1 dBTP ceiling.", Category::Audio, Format::M4a, 128, PODCAST),
137 sound("podcast_ogg", "Podcast ogg", "Vorbis in an ogg, -16 LUFS, -1 dBTP.", Category::Audio, Format::Ogg, 128, PODCAST),165 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] = [
148 loudness: None,176 loudness: None,
149 prores_profile: None,177 prores_profile: None,
150 hdr: HdrTransfer::Sdr,178 hdr: HdrTransfer::Sdr,
179+ qp: None,
180+ keyframe_s: None,
181+ faststart: false,
151 },182 },
152 Preset {183 Preset {
153 id: "archive_prores",184 id: "archive_prores",
@@ -161,6 +192,9 @@ static TABLE: [Preset; 15] = [
161 loudness: None,192 loudness: None,
162 prores_profile: Some(ProResProfile::Hq),193 prores_profile: Some(ProResProfile::Hq),
163 hdr: HdrTransfer::Sdr,194 hdr: HdrTransfer::Sdr,
195+ qp: None,
196+ keyframe_s: None,
197+ faststart: false,
164 },198 },
165 Preset {199 Preset {
166 id: "hdr10_hevc",200 id: "hdr10_hevc",
@@ -174,6 +208,9 @@ static TABLE: [Preset; 15] = [
174 loudness: None,208 loudness: None,
175 prores_profile: None,209 prores_profile: None,
176 hdr: HdrTransfer::Pq,210 hdr: HdrTransfer::Pq,
211+ qp: None,
212+ keyframe_s: None,
213+ faststart: false,
177 },214 },
178 sound("archive_flac", "Archive FLAC", "Lossless FLAC of the mix.", Category::Archive, Format::Flac, 320, None),215 sound("archive_flac", "Archive FLAC", "Lossless FLAC of the mix.", Category::Archive, Format::Flac, 320, None),
179 sound("archive_wav", "Archive WAV", "16-bit PCM WAV of the mix.", Category::Archive, Format::Wav, 320, None),216 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 {
209 loudness: preset.loudness,246 loudness: preset.loudness,
210 prores_profile: preset.prores_profile.unwrap_or(base.prores_profile),247 prores_profile: preset.prores_profile.unwrap_or(base.prores_profile),
211 hdr: HdrOutput { transfer: preset.hdr, ..HdrOutput::default() },248 hdr: HdrOutput { transfer: preset.hdr, ..HdrOutput::default() },
249+ qp: preset.qp.or(base.qp),
250+ keyframe_s: preset.keyframe_s.or(base.keyframe_s),
251+ faststart: preset.faststart || base.faststart,
212 ..base252 ..base
213 }253 }
214 }254 }
crates/engine/src/hw.rsmodified+11 -4
@@ -495,7 +495,7 @@ impl HwEncoder {
495 /// is unavailable -- no child binary, no driver, dimensions the driver495 /// is unavailable -- no child binary, no driver, dimensions the driver
496 /// refuses, *or a child that died opening any of it* -- and the caller falls496 /// refuses, *or a child that died opening any of it* -- and the caller falls
497 /// back to the software encoder.497 /// back to the software encoder.
498- pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option<Self> {498+ pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option<u32>) -> Option<Self> {
499 Self::seated(499 Self::seated(
500 Seat::H264,500 Seat::H264,
501 width,501 width,
@@ -504,6 +504,7 @@ impl HwEncoder {
504 fps_den,504 fps_den,
505 rate,505 rate,
506 ColorDescription::default(),506 ColorDescription::default(),
507+ gop,
507 )508 )
508 }509 }
509 510
@@ -521,13 +522,14 @@ impl HwEncoder {
521 fps_den,522 fps_den,
522 rate,523 rate,
523 ColorDescription::default(),524 ColorDescription::default(),
525+ None,
524 )526 )
525 }527 }
526 528
527 /// The same, coding AV1 instead. `None` on a child or a GPU with no AV1529 /// The same, coding AV1 instead. `None` on a child or a GPU with no AV1
528 /// encoder, and the caller's software AV1 encoder takes the export without530 /// encoder, and the caller's software AV1 encoder takes the export without
529 /// saying anything about it.531 /// saying anything about it.
530- pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option<Self> {532+ pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option<u32>) -> Option<Self> {
531 Self::seated(533 Self::seated(
532 Seat::Av1,534 Seat::Av1,
533 width,535 width,
@@ -536,6 +538,7 @@ impl HwEncoder {
536 fps_den,538 fps_den,
537 rate,539 rate,
538 ColorDescription::default(),540 ColorDescription::default(),
541+ gop,
539 )542 )
540 }543 }
541 544
@@ -549,8 +552,9 @@ impl HwEncoder {
549 fps_den: u32,552 fps_den: u32,
550 rate: SeatRate,553 rate: SeatRate,
551 colour: ColorDescription,554 colour: ColorDescription,
555+ gop: Option<u32>,
552 ) -> Option<Self> {556 ) -> Option<Self> {
553- Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour)557+ Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop)
554 }558 }
555 559
556 /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`]560 /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`]
@@ -563,9 +567,10 @@ impl HwEncoder {
563 rate: SeatRate,567 rate: SeatRate,
564 colour: ColorDescription,568 colour: ColorDescription,
565 ) -> Option<Self> {569 ) -> Option<Self> {
566- Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour)570+ Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None)
567 }571 }
568 572
573+ #[allow(clippy::too_many_arguments)]
569 fn seated(574 fn seated(
570 seat: Seat,575 seat: Seat,
571 width: u32,576 width: u32,
@@ -574,6 +579,7 @@ impl HwEncoder {
574 fps_den: u32,579 fps_den: u32,
575 rate: SeatRate,580 rate: SeatRate,
576 colour: ColorDescription,581 colour: ColorDescription,
582+ gop: Option<u32>,
577 ) -> Option<Self> {583 ) -> Option<Self> {
578 let open = Open {584 let open = Open {
579 seat,585 seat,
@@ -583,6 +589,7 @@ impl HwEncoder {
583 fps_den,589 fps_den,
584 rate,590 rate,
585 colour,591 colour,
592+ gop,
586 };593 };
587 // No child binary beside the executable means no hardware seat at all:594 // No child binary beside the executable means no hardware seat at all:
588 // `Remote::spawn` answers `None` before a process is forked.595 // `Remote::spawn` answers `None` before a process is forked.
crates/engine/src/hwproc.rsmodified+9 -0
@@ -135,6 +135,8 @@ pub struct Open {
135 /// What the sequence header will say the samples mean. Only the HEVC seat135 /// What the sequence header will say the samples mean. Only the HEVC seat
136 /// takes one; the others ignore it.136 /// takes one; the others ignore it.
137 pub colour: ColorDescription,137 pub colour: ColorDescription,
138+ /// Pictures between key frames; `None` is the seat's own two seconds.
139+ pub gop: Option<u32>,
138 }140 }
139 141
140 impl Open {142 impl Open {
@@ -167,6 +169,7 @@ impl Open {
167 SeatRate::Bitrate(bps) => [0, bps],169 SeatRate::Bitrate(bps) => [0, bps],
168 SeatRate::ConstantQp(qp) => [1, u64::from(qp)],170 SeatRate::ConstantQp(qp) => [1, u64::from(qp)],
169 }.map(|v| v.to_string()))171 }.map(|v| v.to_string()))
172+ .chain(std::iter::once(self.gop.unwrap_or(0).to_string()))
170 .collect()173 .collect()
171 }174 }
172 175
@@ -200,6 +203,10 @@ impl Open {
200 },203 },
201 full_range: n(7)? != 0,204 full_range: n(7)? != 0,
202 },205 },
206+ gop: match n(10)? {
207+ 0 => None,
208+ gop => Some(gop),
209+ },
203 })210 })
204 }211 }
205 212
@@ -810,9 +817,11 @@ mod tests {
810 transfer: Transfer::Pq,817 transfer: Transfer::Pq,
811 full_range: true,818 full_range: true,
812 },819 },
820+ gop: Some(15),
813 };821 };
814 let back = Open::from_argv(&open.argv()).expect("parse");822 let back = Open::from_argv(&open.argv()).expect("parse");
815 assert!(back.seat == Seat::Hevc);823 assert!(back.seat == Seat::Hevc);
824+ assert_eq!(back.gop, Some(15));
816 assert_eq!(825 assert_eq!(
817 (back.width, back.height, back.fps_num, back.fps_den),826 (back.width, back.height, back.fps_num, back.fps_den),
818 (1920, 1080, 30000, 1001)827 (1920, 1080, 30000, 1001)
crates/engine/src/mux.rsmodified+56 -7
@@ -13,7 +13,7 @@
13 13
14 use std::collections::VecDeque;14 use std::collections::VecDeque;
15 use std::fs::File;15 use std::fs::File;
16-use std::io::{BufWriter, Seek, SeekFrom, Write};16+use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
17 use std::path::Path;17 use std::path::Path;
18 18
19 use ec_core::{19 use ec_core::{
@@ -121,11 +121,44 @@ const AUDIO_STREAM: u32 = 1;
121 /// the sound from timeline frame 0 and does not run it 21 ms late.121 /// the sound from timeline frame 0 and does not run it 21 ms late.
122 const AAC_PRIMING: u32 = 1024;122 const AAC_PRIMING: u32 = 1024;
123 123
124+/// The file an mp4 is written to: buffered, and readable back for a faststart file.
125+struct Out(BufWriter<File>);
126+
127+impl Out {
128+ fn create(path: &Path) -> std::io::Result<Self> {
129+ let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(path)?;
130+ Ok(Self(BufWriter::new(file)))
131+ }
132+}
133+
134+impl Write for Out {
135+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
136+ self.0.write(buf)
137+ }
138+
139+ fn flush(&mut self) -> std::io::Result<()> {
140+ self.0.flush()
141+ }
142+}
143+
144+impl Read for Out {
145+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
146+ self.0.flush()?;
147+ self.0.get_mut().read(buf)
148+ }
149+}
150+
151+impl Seek for Out {
152+ fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
153+ self.0.seek(pos)
154+ }
155+}
156+
124 /// Writes one H.264, HEVC or AV1 track plus an optional AAC track, through157 /// Writes one H.264, HEVC or AV1 track plus an optional AAC track, through
125 /// `ec-mp4`'s muxer. Timing is carried per sample: every sample is handed over158 /// `ec-mp4`'s muxer. Timing is carried per sample: every sample is handed over
126 /// with its exact decode time and duration, so the tracks cannot drift.159 /// with its exact decode time and duration, so the tracks cannot drift.
127 pub struct Mp4Muxer {160 pub struct Mp4Muxer {
128- writer: ec_mp4::Mp4Muxer<BufWriter<File>>,161+ writer: ec_mp4::Mp4Muxer<Out>,
129 frame_duration: u32,162 frame_duration: u32,
130 /// Whether the file carries a picture track. A sound-only file163 /// Whether the file carries a picture track. A sound-only file
131 /// ([`Mp4Muxer::create_audio_only`]) has none, and then the audio is the164 /// ([`Mp4Muxer::create_audio_only`]) has none, and then the audio is the
@@ -184,6 +217,8 @@ pub struct Mp4Muxer {
184 /// The sound's exact length in PCM frames, where the caller knows it217 /// The sound's exact length in PCM frames, where the caller knows it
185 /// ([`Mp4Muxer::set_audio_frames`]). Only an audio-only file reads it.218 /// ([`Mp4Muxer::set_audio_frames`]). Only an audio-only file reads it.
186 audio_frames: Option<u64>,219 audio_frames: Option<u64>,
220+ /// Whether the file is laid out for streaming ([`Mp4Muxer::set_faststart`]).
221+ faststart: bool,
187 }222 }
188 223
189 /// The H.273 colour description of a picture, as the `colr` box states it.224 /// The H.273 colour description of a picture, as the `colr` box states it.
@@ -254,6 +289,13 @@ fn mp4_language(language: &str) -> String {
254 289
255 290
256 impl Mp4Muxer {291 impl Mp4Muxer {
292+ /// Lays the file out `ftyp`, `moov`, `mdat` so a player can start before the end. Set it before
293+ /// [`finish`](Mp4Muxer::finish), which then reads the `mdat` back to move it.
294+ pub fn set_faststart(&mut self, on: bool) {
295+ self.faststart = on;
296+ self.writer.set_faststart(on);
297+ }
298+
257 /// Declares the sound's exact length in PCM frames per channel, for an299 /// Declares the sound's exact length in PCM frames per channel, for an
258 /// audio-only file: its `elst` plays `frames` samples from the priming and300 /// audio-only file: its `elst` plays `frames` samples from the priming and
259 /// stops there, so the file says what was exported and not what the last301 /// stops there, so the file says what was exported and not what the last
@@ -274,7 +316,7 @@ impl Mp4Muxer {
274 false => (*b"isom", &[*b"isom", *b"iso2", *b"mp41"]),316 false => (*b"isom", &[*b"isom", *b"iso2", *b"mp41"]),
275 };317 };
276 let writer = ec_mp4::Mp4Muxer::with_brands(318 let writer = ec_mp4::Mp4Muxer::with_brands(
277- BufWriter::new(File::create(path)?),319+ Out::create(path)?,
278 major,320 major,
279 compatible,321 compatible,
280 )322 )
@@ -297,6 +339,7 @@ impl Mp4Muxer {
297 flushed_video_ticks: 0,339 flushed_video_ticks: 0,
298 audio_rate: 0,340 audio_rate: 0,
299 audio_frames: None,341 audio_frames: None,
342+ faststart: false,
300 };343 };
301 muxer.add_audio_track(audio)?;344 muxer.add_audio_track(audio)?;
302 Ok(muxer)345 Ok(muxer)
@@ -381,7 +424,7 @@ impl Mp4Muxer {
381 }424 }
382 425
383 let (timescale, frame_duration) = frame_timing(frame_rate)?;426 let (timescale, frame_duration) = frame_timing(frame_rate)?;
384- let mut writer = ec_mp4::Mp4Muxer::new(BufWriter::new(File::create(path)?))427+ let mut writer = ec_mp4::Mp4Muxer::new(Out::create(path)?)
385 .map_err(mp4_error)?;428 .map_err(mp4_error)?;
386 let video_info = StreamInfo::new(429 let video_info = StreamInfo::new(
387 VIDEO_STREAM,430 VIDEO_STREAM,
@@ -422,6 +465,7 @@ impl Mp4Muxer {
422 flushed_video_ticks: 0,465 flushed_video_ticks: 0,
423 audio_rate: 0,466 audio_rate: 0,
424 audio_frames: None,467 audio_frames: None,
468+ faststart: false,
425 };469 };
426 if let Some(audio) = audio {470 if let Some(audio) = audio {
427 muxer.add_audio_track(audio)?;471 muxer.add_audio_track(audio)?;
@@ -767,10 +811,15 @@ impl Mp4Muxer {
767 .map_err(mp4_error)?;811 .map_err(mp4_error)?;
768 }812 }
769 }813 }
814+ let faststart = self.faststart;
770 let mut writer = self.writer;815 let mut writer = self.writer;
771- ec_core::Muxer::finish(&mut writer).map_err(mp4_error)?;816+ if faststart {
772- // Not a `drop`: a `BufWriter` swallows the error of flushing on drop.817+ writer.finish_faststart().map_err(mp4_error)?.0.flush()?;
773- writer.into_inner().flush()?;818+ } else {
819+ ec_core::Muxer::finish(&mut writer).map_err(mp4_error)?;
820+ // Not a `drop`: a `BufWriter` swallows the error of flushing on drop.
821+ writer.into_inner().0.flush()?;
822+ }
774 Ok(())823 Ok(())
775 }824 }
776 }825 }
crates/engine/tests/export.rsmodified+3 -3
@@ -772,7 +772,7 @@ fn exports_audio_alongside_the_video() {
772 fn hardware_access_units_repack_into_mp4() {772 fn hardware_access_units_repack_into_mp4() {
773 let (w, h) = (640u32, 480u32);773 let (w, h) = (640u32, 480u32);
774 let mut encoder =774 let mut encoder =
775- HwEncoder::open(w, h, 30, 1, SeatRate::Bitrate(4_000_000)).expect("no hardware encode plugin/driver");775+ HwEncoder::open(w, h, 30, 1, SeatRate::Bitrate(4_000_000), None).expect("no hardware encode plugin/driver");
776 let out = out_path("hwmux");776 let out = out_path("hwmux");
777 let mut muxer: Option<Mp4Muxer> = None;777 let mut muxer: Option<Mp4Muxer> = None;
778 let mut written = 0;778 let mut written = 0;
@@ -1919,7 +1919,7 @@ fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() {
1919 // No `VE_HW_TIMEOUT_MS` at all: the wait is the one a person's export gets.1919 // No `VE_HW_TIMEOUT_MS` at all: the wait is the one a person's export gets.
1920 injected_with(None, Some("10"), None, || {1920 injected_with(None, Some("10"), None, || {
1921 let mut encoder =1921 let mut encoder =
1922- HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000)).expect("the stand-in seat opened");1922+ HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000), None).expect("the stand-in seat opened");
1923 let (y, u, v) = synthetic(0, width as usize, height as usize);1923 let (y, u, v) = synthetic(0, width as usize, height as usize);
1924 for frame in 0..10 {1924 for frame in 0..10 {
1925 assert!(1925 assert!(
@@ -2058,7 +2058,7 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() {
2058 let (width, height) = (320u32, 240u32);2058 let (width, height) = (320u32, 240u32);
2059 injected(Some("1"), None, || {2059 injected(Some("1"), None, || {
2060 let mut encoder =2060 let mut encoder =
2061- HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000)).expect("the stand-in seat opened");2061+ HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000), None).expect("the stand-in seat opened");
2062 let (y, u, v) = synthetic(0, width as usize, height as usize);2062 let (y, u, v) = synthetic(0, width as usize, height as usize);
2063 assert!(2063 assert!(
2064 encoder.encode(&y, &u, &v, width, height, false).is_ok(),2064 encoder.encode(&y, &u, &v, width, height, false).is_ok(),
crates/engine/tests/hw_encode.rsmodified+4 -4
@@ -45,7 +45,7 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<
45 /// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus45 /// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus
46 /// the number of access units the plugin handed back.46 /// the number of access units the plugin handed back.
47 fn encode(width: u32, height: u32, count: u32) -> Option<(Vec<u8>, u32)> {47 fn encode(width: u32, height: u32, count: u32) -> Option<(Vec<u8>, u32)> {
48- let mut encoder = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE))?;48+ let mut encoder = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE), None)?;
49 let mut stream = Vec::new();49 let mut stream = Vec::new();
50 let mut units = 0;50 let mut units = 0;
51 // Timed around the plugin call only: building the synthetic picture is not51 // 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() {
249 let asset =249 let asset =
250 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");250 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
251 let (width, height) = (1280u32, 720u32);251 let (width, height) = (1280u32, 720u32);
252- let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE)) else {252+ let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE), None) else {
253 println!("no hardware encoder here -- skipping");253 println!("no hardware encoder here -- skipping");
254 return;254 return;
255 };255 };
@@ -367,13 +367,13 @@ fn decode_and_encode_load_independently() {
367 let asset =367 let asset =
368 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");368 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
369 assert!(369 assert!(
370- HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE)).is_some(),370+ HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE), None).is_some(),
371 "encode table"371 "encode table"
372 );372 );
373 assert!(HwSession::open(&asset).is_some(), "decode table");373 assert!(HwSession::open(&asset).is_some(), "decode table");
374 // Order reversed: neither table's `OnceLock` may have primed the other.374 // Order reversed: neither table's `OnceLock` may have primed the other.
375 assert!(HwSession::open(&asset).is_some());375 assert!(HwSession::open(&asset).is_some());
376- assert!(HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE)).is_some());376+ assert!(HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE), None).is_some());
377 }377 }
378 378
379 /// Per slice: `(is_idr, frame_num, pic_order_cnt_lsb)`, read by [`slice_counters`].379 /// Per slice: `(is_idr, frame_num, pic_order_cnt_lsb)`, read by [`slice_counters`].
crates/mcp/src/help.rsmodified+2 -2
@@ -226,7 +226,7 @@ LANES
226 226
227 const EXPORT: &str = "\227 const EXPORT: &str = "\
228 EXPORT228 EXPORT
229- 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?}229+ 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?}
230 returns job:<n> at once. Poll it with export_status {job?}; export_cancel {job} stops it and deletes the partial file.230 returns job:<n> at once. Poll it with export_status {job?}; export_cancel {job} stops it and deletes the partial file.
231 out: the file to write; ~/ is expanded and its folder must exist. The extension picks the format:231 out: the file to write; ~/ is expanded and its folder must exist. The extension picks the format:
232 .mp4 mp4 · .mkv av1 · .webm · .wav · .flac · .mp3 · .ogg · .m4a · .opus · .mov prores. Refuses an existing file unless overwrite:true.232 .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
240 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.240 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.
241 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.241 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.
242 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.242 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.
243- 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.243+ 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.
244 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.244 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.
245 Captions: burn_captions draws one track into the picture, so every player and WebM show it. subtitles adds soft245 Captions: burn_captions draws one track into the picture, so every player and WebM show it. subtitles adds soft
246 tracks a player can switch off (WebM has none). Both together: burned and soft. burn_captions alone: no soft track.246 tracks a player can switch off (WebM has none). Both together: burned and soft. burn_captions alone: no soft track.
crates/mcp/src/tools/export.rsmodified+40 -4
@@ -36,7 +36,7 @@ pub fn tools() -> Vec<Tool> {
36 },36 },
37 Tool {37 Tool {
38 name: "export_presets",38 name: "export_presets",
39- description: "List the export presets export_start { preset: \"<id>\" } takes: id, label and the settings each sets (format, bitrate_kbps, audio_kbps, size, bit_depth, loudness). Explicit export_start arguments override the preset.",39+ description: "List the export presets export_start { preset: \"<id>\" } 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.",
40 schema: presets_schema,40 schema: presets_schema,
41 run: export_presets,41 run: export_presets,
42 },42 },
@@ -168,6 +168,9 @@ fn preset_json(p: &engine::export_presets::Preset) -> Value {
168 "audio_kbps": p.audio_kbps,168 "audio_kbps": p.audio_kbps,
169 "size": p.target.size.map(|(w, h)| format!("{w}x{h}")),169 "size": p.target.size.map(|(w, h)| format!("{w}x{h}")),
170 "bit_depth": p.video_bit_depth,170 "bit_depth": p.video_bit_depth,
171+ "qp": p.qp,
172+ "keyframe_s": p.keyframe_s,
173+ "faststart": p.faststart,
171 "prores_profile": p.prores_profile.map(prores_name),174 "prores_profile": p.prores_profile.map(prores_name),
172 "hdr": hdr_name(p.hdr),175 "hdr": hdr_name(p.hdr),
173 "loudness": p.loudness.map(|l| json!({ "lufs": l.lufs, "true_peak_dbtp": l.true_peak_dbtp })),176 "loudness": p.loudness.map(|l| json!({ "lufs": l.lufs, "true_peak_dbtp": l.true_peak_dbtp })),
@@ -259,7 +262,7 @@ fn start_schema() -> Value {
259 "preset": {262 "preset": {
260 "type": "string",263 "type": "string",
261 "enum": engine::export_presets::presets().iter().map(|p| p.id).collect::<Vec<_>>(),264 "enum": engine::export_presets::presets().iter().map(|p| p.id).collect::<Vec<_>>(),
262- "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."265+ "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."
263 },266 },
264 "loudness": {267 "loudness": {
265 "type": "number",268 "type": "number",
@@ -320,6 +323,16 @@ fn start_schema() -> Value {
320 "maximum": 51,323 "maximum": 51,
321 "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."324 "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."
322 },325 },
326+ "keyframe_s": {
327+ "type": "number",
328+ "minimum": 0.1,
329+ "maximum": 10,
330+ "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."
331+ },
332+ "faststart": {
333+ "type": "boolean",
334+ "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."
335+ },
323 "audio_kbps": {336 "audio_kbps": {
324 "type": "integer",337 "type": "integer",
325 "enum": [128, 192, 256, 320, 384],338 "enum": [128, 192, 256, 320, 384],
@@ -1541,8 +1554,9 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1541 Some(k) => Some(k.saturating_mul(1000)),1554 Some(k) => Some(k.saturating_mul(1000)),
1542 None => None,1555 None => None,
1543 };1556 };
1557+ let intra_only = opt_bool(args, "intra_only").unwrap_or(false);
1544 let qp = match opt_u64(args, "qp") {1558 let qp = match opt_u64(args, "qp") {
1545- None => None,1559+ None => preset.and_then(|p| p.qp).filter(|_| bitrate.is_none() && !sound_only),
1546 Some(q) if q <= 51 => Some(q as u32),1560 Some(q) if q <= 51 => Some(q as u32),
1547 Some(q) => return Reply::err(format!("qp {q} is not 0 to 51")),1561 Some(q) => return Reply::err(format!("qp {q} is not 0 to 51")),
1548 };1562 };
@@ -1564,6 +1578,26 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1564 if qp.is_some() && seat == EncoderSeat::Software && !format.is_hevc() {1578 if qp.is_some() && seat == EncoderSeat::Software && !format.is_hevc() {
1565 return Reply::err("qp with seat software: only the software HEVC encoder writes a constant QP; use seat auto or hardware for H.264");1579 return Reply::err("qp with seat software: only the software HEVC encoder writes a constant QP; use seat auto or hardware for H.264");
1566 }1580 }
1581+ let keyframe_s = match args.get("keyframe_s") {
1582+ None | Some(Value::Null) => preset.and_then(|p| p.keyframe_s).filter(|_| !intra_only && !sound_only),
1583+ Some(v) => match v.as_f64() {
1584+ Some(secs) if (0.1..=10.0).contains(&secs) => Some(secs),
1585+ _ => return Reply::err("keyframe_s is a number of seconds, from 0.1 to 10"),
1586+ },
1587+ };
1588+ if keyframe_s.is_some() && intra_only {
1589+ return Reply::err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one");
1590+ }
1591+ if keyframe_s.is_some() && sound_only {
1592+ return Reply::err("keyframe_s sets the picture's key frames, and this export is the sound alone");
1593+ }
1594+ let faststart = opt_bool(args, "faststart").unwrap_or(preset.is_some_and(|p| p.faststart));
1595+ if faststart && !format.is_mp4_family() {
1596+ return Reply::err(format!(
1597+ "faststart lays out an mp4, and {} is not one: use mp4, hevc-mp4, av1-mp4 or m4a",
1598+ format_name(format)
1599+ ));
1600+ }
1567 let audio_kbps = match opt_u64(args, "audio_kbps") {1601 let audio_kbps = match opt_u64(args, "audio_kbps") {
1568 None => None,1602 None => None,
1569 Some(k) => {1603 Some(k) => {
@@ -1725,7 +1759,9 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1725 qp,1759 qp,
1726 seat,1760 seat,
1727 format,1761 format,
1728- intra_only: opt_bool(args, "intra_only").unwrap_or(false),1762+ intra_only,
1763+ keyframe_s,
1764+ faststart,
1729 audio_kbps,1765 audio_kbps,
1730 subtitles,1766 subtitles,
1731 no_soft_subtitles: no_soft,1767 no_soft_subtitles: no_soft,