forge
Explore
Log in

Don't you dare go Hollow

✨ export_start takes qp for a constant-quantiser hardware (and software HEVC) export, AAC goes to 384 kbps, and the GPU's HEVC seat codes I+P GOPs instead of every picture an IDR

Browse files at this commit

53251aa245879da1d4736c462366c16fee4550efAhmet Kaan GümüşParent: eb998b7
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, audio_kbps (128/192/256/320), 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), 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/engine-hw/src/enc_ec.rsmodified+13 -14
@@ -16,6 +16,7 @@ use ec_hw::{Encoder, H264Profile, I420};
16 use ec_va::{PrimeLayer, PrimeObject, PrimeSurface};16 use ec_va::{PrimeLayer, PrimeObject, PrimeSurface};
17 17
18 use engine::hw::{DmaFrame, VhDma};18 use engine::hw::{DmaFrame, VhDma};
19+use engine::hwproc::SeatRate;
19 20
20 /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters.21 /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters.
21 const FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12");22 const FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12");
@@ -44,7 +45,7 @@ pub(crate) struct EcOpen {
44 pub height: u32,45 pub height: u32,
45 pub fps_num: u32,46 pub fps_num: u32,
46 pub fps_den: u32,47 pub fps_den: u32,
47- pub bitrate: u64,48+ pub rate: SeatRate,
48 /// 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`).
49 pub intra_only: bool,50 pub intra_only: bool,
50 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.51 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.
@@ -59,7 +60,7 @@ impl EcEncSession {
59 height,60 height,
60 fps_num,61 fps_num,
61 fps_den,62 fps_den,
62- bitrate,63+ rate,
63 intra_only,64 intra_only,
64 colour,65 colour,
65 } = req;66 } = req;
@@ -74,24 +75,22 @@ impl EcEncSession {
74 if codec == EncCodec::H265 && (width < 384 || height < 384) {75 if codec == EncCodec::H265 && (width < 384 || height < 384) {
75 return None;76 return None;
76 }77 }
77- if fps_num == 0 || fps_den == 0 || bitrate == 0 {78+ if fps_num == 0 || fps_den == 0 || rate == SeatRate::Bitrate(0) {
78 return None;79 return None;
79 }80 }
80 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;81 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
81 let mut config = EncoderConfig::new(codec, width, height);82 let mut config = EncoderConfig::new(codec, width, height);
82 config.framerate = (framerate, 1);83 config.framerate = (framerate, 1);
83- config.bitrate = u32::try_from(bitrate).unwrap_or(u32::MAX);84+ if let SeatRate::Bitrate(bitrate) = rate {
84- config.gop_size = match codec {85+ config.bitrate = u32::try_from(bitrate).unwrap_or(u32::MAX);
85- // Every HEVC picture is an IDR: a GOP's P slices come out of this86+ }
86- // driver undecodable (measured 2026-08-13 on radeonsi), so the seat87+ config.gop_size = u32::from(crate::gop_limit(framerate, intra_only));
87- // is intra-only exactly as the software one is.88+ config.rate_control = match (codec, rate) {
88- EncCodec::H265 => 1,89+ (EncCodec::Av1, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp: qp.min(51) * 255 / 51 },
89- _ => u32::from(crate::gop_limit(framerate, intra_only)),90+ (_, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp },
90- };
91- config.rate_control = match codec {
92 // Constant quality at 128 of 255, the AV1 rate control measured.91 // Constant quality at 128 of 255, the AV1 rate control measured.
93- EncCodec::Av1 => RateControlMode::ConstantQp { qp: 128 },92+ (EncCodec::Av1, SeatRate::Bitrate(_)) => RateControlMode::ConstantQp { qp: 128 },
94- _ => RateControlMode::ConstantBitrate,93+ (_, SeatRate::Bitrate(_)) => RateControlMode::ConstantBitrate,
95 };94 };
96 if codec == EncCodec::H264 {95 if codec == EncCodec::H264 {
97 // Main, not the High default: the seat's tests pin the profile.96 // Main, not the High default: the seat's tests pin the profile.
crates/engine-hw/src/lib.rsmodified+6 -5
@@ -802,12 +802,12 @@ pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option<EcEncSession>
802 Seat::H264 => (EcCodec::H264, false, None),802 Seat::H264 => (EcCodec::H264, false, None),
803 Seat::Intra => (EcCodec::H264, true, None),803 Seat::Intra => (EcCodec::H264, true, None),
804 Seat::Av1 => (EcCodec::Av1, false, None),804 Seat::Av1 => (EcCodec::Av1, false, None),
805- Seat::Hevc => {805+ Seat::Hevc | Seat::HevcIntra => {
806 let (p, t, m) = open.colour.codes();806 let (p, t, m) = open.colour.codes();
807 let narrow = |code: u16| u8::try_from(code).unwrap_or(u8::MAX);807 let narrow = |code: u16| u8::try_from(code).unwrap_or(u8::MAX);
808 (808 (
809 EcCodec::H265,809 EcCodec::H265,
810- true,810+ open.seat == Seat::HevcIntra,
811 Some((narrow(p), narrow(t), narrow(m), open.colour.full_range)),811 Some((narrow(p), narrow(t), narrow(m), open.colour.full_range)),
812 )812 )
813 }813 }
@@ -818,7 +818,7 @@ pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option<EcEncSession>
818 height: open.height,818 height: open.height,
819 fps_num: open.fps_num,819 fps_num: open.fps_num,
820 fps_den: open.fps_den,820 fps_den: open.fps_den,
821- bitrate: open.bitrate,821+ rate: open.rate,
822 intra_only,822 intra_only,
823 colour,823 colour,
824 })824 })
@@ -827,6 +827,7 @@ pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option<EcEncSession>
827 #[cfg(test)]827 #[cfg(test)]
828 mod tests {828 mod tests {
829 use super::*;829 use super::*;
830+ use engine::hwproc::SeatRate;
830 831
831 /// The one number that decides whether a hardware file is intra-only, and832 /// The one number that decides whether a hardware file is intra-only, and
832 /// the one this seat got wrong: a proxy asks for a group of one picture, so833 /// the one this seat got wrong: a proxy asks for a group of one picture, so
@@ -865,7 +866,7 @@ mod tests {
865 height: 240,866 height: 240,
866 fps_num: 30,867 fps_num: 30,
867 fps_den: 1,868 fps_den: 1,
868- bitrate: 2_000_000,869+ rate: SeatRate::Bitrate(2_000_000),
869 intra_only: true,870 intra_only: true,
870 colour: None,871 colour: None,
871 };872 };
@@ -946,7 +947,7 @@ mod tests {
946 height: 240,947 height: 240,
947 fps_num: 30,948 fps_num: 30,
948 fps_den: 1,949 fps_den: 1,
949- bitrate: 2_000_000,950+ rate: SeatRate::Bitrate(2_000_000),
950 intra_only: true,951 intra_only: true,
951 colour: None,952 colour: None,
952 };953 };
crates/engine/src/export.rsmodified+82 -63
@@ -7,7 +7,7 @@
7 //! them, rate-controlled when the settings carry a bitrate and at constant QP7 //! them, rate-controlled when the settings carry a bitrate and at constant QP
8 //! when they do not. [`ExportSettings::intra_only`] makes every picture an IDR8 //! when they do not. [`ExportSettings::intra_only`] makes every picture an IDR
9 //! instead -- an intraframe master in the family of ProRes and DNxHD, large9 //! instead -- an intraframe master in the family of ProRes and DNxHD, large
10-//! files and every frame a cut point. The hardware HEVC seat codes intra only.10+//! files and every frame a cut point.
11 //!11 //!
12 //! Picture and sound are both **copied wherever a copy says exactly what the12 //! Picture and sound are both **copied wherever a copy says exactly what the
13 //! timeline says** — a copy is exact, free and never a generation of loss. For13 //! timeline says** — a copy is exact, free and never a generation of loss. For
@@ -80,6 +80,7 @@ use crate::colorspace::{Chroma, ColorDescription, Matrix, Tags, Transfer};
80 use crate::decode::{I420, Pulled, Wide};80 use crate::decode::{I420, Pulled, Wide};
81 use crate::demux::{Codec, Demuxer, MkvDemuxer, Rotation, VideoMeta};81 use crate::demux::{Codec, Demuxer, MkvDemuxer, Rotation, VideoMeta};
82 use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession};82 use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession};
83+use crate::hwproc::SeatRate;
83 use crate::mux::{84 use crate::mux::{
84 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,85 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
85 };86 };
@@ -142,6 +143,11 @@ const MAX_EXPLICIT_BITRATE: u64 = 50_000_000;
142 /// was given rather than the nearest one `ec-mp3` snaps to.143 /// was given rather than the nearest one `ec-mp3` snaps to.
143 pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320];144 pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320];
144 145
146+/// The sound rate AAC alone may be coded at, above the rows [`AUDIO_KBPS`] offers.
147+pub const AAC_MAX_KBPS: u32 = 384;
148+
149+const QP_SOFTWARE_REFUSAL: &str = "a constant QP (qp) is written by the hardware seat and the software HEVC encoders only: pass seat hardware for this format, or bitrate_kbps for a fixed rate";
150+
145 /// What the sound is coded at when nobody picked: the rate this project wrote151 /// What the sound is coded at when nobody picked: the rate this project wrote
146 /// before the choice existed. 256 and not the encoders' own 128, because an152 /// before the choice existed. 256 and not the encoders' own 128, because an
147 /// export is a master a person edits from again and this is a second lossy153 /// export is a master a person edits from again and this is a second lossy
@@ -543,6 +549,8 @@ pub struct ExportSettings {
543 /// Bits per second, clamped to the same sane range the automatic value uses.549 /// Bits per second, clamped to the same sane range the automatic value uses.
544 /// `None` picks it from the picture size and frame rate. Video only.550 /// `None` picks it from the picture size and frame rate. Video only.
545 pub bitrate: Option<u64>,551 pub bitrate: Option<u64>,
552+ /// A constant quantiser (0..51 for H.264 and HEVC) instead of a bitrate.
553+ pub qp: Option<u32>,
546 /// Which encoder writes the picture ([`EncoderSeat`]). Was a `force_sw`554 /// Which encoder writes the picture ([`EncoderSeat`]). Was a `force_sw`
547 /// flag, which could say "not the GPU" and never "the GPU or say so".555 /// flag, which could say "not the GPU" and never "the GPU or say so".
548 /// [`EncoderSeat::Software`] is what the `VE_SW_ENC` env pin still forces556 /// [`EncoderSeat::Software`] is what the `VE_SW_ENC` env pin still forces
@@ -1247,13 +1255,20 @@ fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
1247 )1255 )
1248 }1256 }
1249 1257
1258+fn rate_of(meta: &VideoMeta, settings: &ExportSettings) -> SeatRate {
1259+ match settings.qp {
1260+ Some(qp) => SeatRate::ConstantQp(qp),
1261+ None => SeatRate::Bitrate(bitrate_of(meta, settings)),
1262+ }
1263+}
1264+
1250 /// The rate the sound codes at: the caller's pick clamped into the offered1265 /// The rate the sound codes at: the caller's pick clamped into the offered
1251 /// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,1266 /// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,
1252 /// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and1267 /// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and
1253 /// not a file worth failing.1268 /// not a file worth failing.
1254 fn audio_kbps_of(settings: &ExportSettings) -> u32 {1269 fn audio_kbps_of(settings: &ExportSettings) -> u32 {
1255 // 384 is above the offered rows, which a preset asks for (YouTube's AAC); MP3 has no such rate.1270 // 384 is above the offered rows, which a preset asks for (YouTube's AAC); MP3 has no such rate.
1256- let ceiling = if settings.format == Format::Mp3 { AUDIO_KBPS[3] } else { 384 };1271+ let ceiling = if settings.format == Format::Mp3 { AUDIO_KBPS[3] } else { AAC_MAX_KBPS };
1257 settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| k.clamp(AUDIO_KBPS[0], ceiling))1272 settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| k.clamp(AUDIO_KBPS[0], ceiling))
1258 }1273 }
1259 1274
@@ -1272,12 +1287,6 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<
1272 if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") {1287 if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") {
1273 return Ok(None);1288 return Ok(None);
1274 }1289 }
1275- // The plugin's HEVC seat codes intra pictures only ([`open_hw_seat`]), so a
1276- // GOP export cannot be had from the GPU. Said here rather than written as an
1277- // intra file under a card that promised I+P.
1278- if settings.seat == EncoderSeat::Hardware && settings.format.is_hevc() && !settings.intra_only {
1279- return Err("hardware HEVC codes intra pictures only and this export is I+P: pick Auto or Software on the export card, or an intra-only export for the GPU".into());
1280- }
1281 let opened = open_hw_seat(meta, settings);1290 let opened = open_hw_seat(meta, settings);
1282 if opened.is_none() && settings.seat == EncoderSeat::Hardware {1291 if opened.is_none() && settings.seat == EncoderSeat::Hardware {
1283 return Err(format!(1292 return Err(format!(
@@ -1294,31 +1303,29 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<
1294 /// this picture, with no policy in it but the AV1 one.1303 /// this picture, with no policy in it but the AV1 one.
1295 fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {1304 fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
1296 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;1305 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
1297- let bitrate = bitrate_of(meta, settings);1306+ let rate = rate_of(meta, settings);
1298 match settings.format {1307 match settings.format {
1299- // Both HEVC formats sit on the plugin's HEVC seat, and it is the1308+ // Both HEVC formats sit on the plugin's HEVC seat, GOP or intra as the
1300- // default again: what it codes is intra-only, the very file the1309+ // export asks. `None` here is the plugin's own "no" -- no entrypoint, or
1301- // software seat writes, so preferring the GPU changes how long an1310+ // a picture under the driver's 384x384 floor -- and the software seat
1302- // export takes and not what comes out of it. What made that untrue for1311+ // takes it. The colour goes in at the open, from the same
1303- // one day was the vendored encoder's parameter sets promising coding1312+ // [`ColorDescription::output`] rule the software seat's VUI and both
1304- // tools the driver was not using; the pictures are now measured against1313+ // containers' tags come from, so the file cannot say one thing in its
1305- // their sources rather than counted1314+ // bitstream and another in its header.
1306- // (`hevc_export::a_1080p_hardware_export_leaves_a_decoder_with_nothing_to_say`).1315+ format if format.is_hevc() && settings.intra_only => HwEncoder::open_hevc_intra(
1307- // `None` here is the plugin's own "no" -- no entrypoint, or a picture1316+ meta.width,
1308- // under the driver's 384x384 floor -- and the software seat takes it.1317+ meta.height,
1309- // The colour goes in at the open, from the same [`ColorDescription::output`]1318+ fps_num,
1310- // rule the software seat's VUI and both containers' tags come from, so1319+ fps_den,
1311- // the file cannot say one thing in its bitstream and another in its1320+ rate,
1312- // header.1321+ ColorDescription::output_sized(meta.width, meta.height),
1313- // The GOP default is software: Auto takes `ec-h265` for an I+P file1322+ ),
1314- // rather than the GPU's intra one, which is what the card says it is.
1315- format if format.is_hevc() && !settings.intra_only => None,
1316 format if format.is_hevc() => HwEncoder::open_hevc(1323 format if format.is_hevc() => HwEncoder::open_hevc(
1317 meta.width,1324 meta.width,
1318 meta.height,1325 meta.height,
1319 fps_num,1326 fps_num,
1320 fps_den,1327 fps_den,
1321- bitrate,1328+ rate,
1322 ColorDescription::output_sized(meta.width, meta.height),1329 ColorDescription::output_sized(meta.width, meta.height),
1323 ),1330 ),
1324 // Asked for by name only, for the reason [`Enc::open_av1`] states in1331 // Asked for by name only, for the reason [`Enc::open_av1`] states in
@@ -1326,7 +1333,7 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder
1326 // AV1 formats sit on it: the container is not the encoder's business.1333 // AV1 formats sit on it: the container is not the encoder's business.
1327 format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None,1334 format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None,
1328 format if format.is_av1() => {1335 format if format.is_av1() => {
1329- HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)1336+ HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate)
1330 }1337 }
1331 // An intra-only H.264 file is a *different seat*, not the same seat with1338 // An intra-only H.264 file is a *different seat*, not the same seat with
1332 // a flag on the pictures: asking this one for a key frame every time1339 // a flag on the pictures: asking this one for a key frame every time
@@ -1337,15 +1344,20 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder
1337 // encoder takes the file -- its `gop_size = 1` writes what was asked1344 // encoder takes the file -- its `gop_size = 1` writes what was asked
1338 // for, slowly, which is the only honest fallback here.1345 // for, slowly, which is the only honest fallback here.
1339 //1346 //
1340- // Only H.264 reaches this arm: the two arms above take every HEVC and1347+ // Only H.264 reaches this arm: the arms above take every HEVC and AV1 format.
1341- // AV1 format, and the HEVC seat is intra-only already.
1342 _ if settings.intra_only => {1348 _ if settings.intra_only => {
1343- HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, bitrate)1349+ HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, rate)
1344 }1350 }
1345- _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),1351+ _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate),
1346 }1352 }
1347 }1353 }
1348 1354
1355+/// True when an Annex B HEVC access unit holds an IRAP picture (NAL types 16..=23).
1356+fn hevc_irap(au: &[u8]) -> bool {
1357+ au.windows(4)
1358+ .any(|w| w[0] == 0 && w[1] == 0 && w[2] == 1 && (16..=23).contains(&((w[3] >> 1) & 0x3F)))
1359+}
1360+
1349 /// What a hardware encode is called wherever one is named -- the card's line1361 /// What a hardware encode is called wherever one is named -- the card's line
1350 /// before the export and the progress line during it.1362 /// before the export and the progress line during it.
1351 const HW_LABEL: &str = "HW encode (VA-API)";1363 const HW_LABEL: &str = "HW encode (VA-API)";
@@ -8161,7 +8173,7 @@ enum Enc {
8161 Av1Hw(HwEncoder),8173 Av1Hw(HwEncoder),
8162 /// HEVC on the GPU, through that same plugin -- and intra-only there too,8174 /// HEVC on the GPU, through that same plugin -- and intra-only there too,
8163 /// so this and [`Enc::Hevc`] write the same kind of file.8175 /// so this and [`Enc::Hevc`] write the same kind of file.
8164- HevcHw(HwEncoder),8176+ HevcHw(HwEncoder, bool),
8165 /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes8177 /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes
8166 /// through the span untouched arrives as 16-bit planes off the 10-bit decode8178 /// through the span untouched arrives as 16-bit planes off the 10-bit decode
8167 /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted8179 /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted
@@ -8253,7 +8265,7 @@ impl Enc {
8253 Self::Sw { .. } => video_label(Format::Mp4, false, false),8265 Self::Sw { .. } => video_label(Format::Mp4, false, false),
8254 Self::Av1Hw(_) => video_label(Format::Av1, true, false),8266 Self::Av1Hw(_) => video_label(Format::Av1, true, false),
8255 Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false),8267 Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false),
8256- Self::HevcHw(_) => video_label(Format::Hevc, true, true),8268+ Self::HevcHw(_, intra) => video_label(Format::Hevc, true, *intra),
8257 Self::Hevc(_) => video_label(Format::Hevc, false, true),8269 Self::Hevc(_) => video_label(Format::Hevc, false, true),
8258 Self::HevcGop(_) => video_label(Format::Hevc, false, false),8270 Self::HevcGop(_) => video_label(Format::Hevc, false, false),
8259 Self::ProRes { .. } => video_label(Format::ProRes, false, true),8271 Self::ProRes { .. } => video_label(Format::ProRes, false, true),
@@ -8301,6 +8313,9 @@ impl Enc {
8301 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); }8313 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); }
8302 return Ok(Self::Hw(hw));8314 return Ok(Self::Hw(hw));
8303 }8315 }
8316+ if settings.qp.is_some() {
8317+ return Err(QP_SOFTWARE_REFUSAL.into());
8318+ }
8304 // H.264 codes 16x16 macroblocks, and ec-h264's floor is the8319 // H.264 codes 16x16 macroblocks, and ec-h264's floor is the
8305 // macroblock itself -- the old encoder took any positive even size.8320 // macroblock itself -- the old encoder took any positive even size.
8306 // Named here, where a card can show it, rather than let the encoder's8321 // Named here, where a card can show it, rather than let the encoder's
@@ -8395,6 +8410,9 @@ impl Enc {
8395 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); }8410 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); }
8396 return Ok(Self::Av1Hw(hw));8411 return Ok(Self::Av1Hw(hw));
8397 }8412 }
8413+ if settings.qp.is_some() {
8414+ return Err(QP_SOFTWARE_REFUSAL.into());
8415+ }
8398 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software AV1 (rav1e)"); }8416 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software AV1 (rav1e)"); }
8399 // Seconds per frame, which is what `frame_timing` already has as an8417 // Seconds per frame, which is what `frame_timing` already has as an
8400 // exact rational -- 1001/24000 rather than a rounded 23.976.8418 // exact rational -- 1001/24000 rather than a rounded 23.976.
@@ -8478,11 +8496,12 @@ impl Enc {
8478 /// encode entrypoint. Silent either way, because both write the same kind8496 /// encode entrypoint. Silent either way, because both write the same kind
8479 /// of file.8497 /// of file.
8480 ///8498 ///
8481- /// The default is I+P GOPs on the software seat ([`Enc::open_hevc_gop`]).8499+ /// The default is I+P GOPs, on the hardware seat where there is one and on
8482- /// With [`ExportSettings::intra_only`] it is intra: every picture an IDR,8500+ /// the software seat ([`Enc::open_hevc_gop`]) where there is not. With
8483- /// on the hardware seat where there is one and on the lanes below where8501+ /// [`ExportSettings::intra_only`] it is intra: every picture an IDR, on the
8484- /// there is not -- an intraframe master in the shape of ProRes or DNxHD,8502+ /// hardware seat where there is one and on the lanes below where there is
8485- /// large files, every frame a cut point.8503+ /// not -- an intraframe master in the shape of ProRes or DNxHD, large
8504+ /// files, every frame a cut point.
8486 ///8505 ///
8487 /// The picture is coded at its own size and padded to whole minimum coding8506 /// The picture is coded at its own size and padded to whole minimum coding
8488 /// blocks *by the encoder*, which crops the padding back off with the SPS8507 /// blocks *by the encoder*, which crops the padding back off with the SPS
@@ -8516,8 +8535,8 @@ impl Enc {
8516 false => hw_seat(meta, settings)?,8535 false => hw_seat(meta, settings)?,
8517 };8536 };
8518 if let Some(hw) = hw {8537 if let Some(hw) = hw {
8519- if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC intra (VA-API plugin)"); }8538+ if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC (VA-API plugin)"); }
8520- return Ok(Self::HevcHw(hw));8539+ return Ok(Self::HevcHw(hw, settings.intra_only));
8521 }8540 }
8522 if !settings.intra_only {8541 if !settings.intra_only {
8523 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); }8542 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); }
@@ -8539,7 +8558,7 @@ impl Enc {
8539 // rate controller. The encoder's own per-picture target-bits mode8558 // rate controller. The encoder's own per-picture target-bits mode
8540 // would chase the number with a correction pass -- named headroom,8559 // would chase the number with a correction pass -- named headroom,
8541 // not behaviour this seat takes silently.8560 // not behaviour this seat takes silently.
8542- cfg.rate_control = RateControl::ConstantQp(hevc_qp(meta, settings));8561+ cfg.rate_control = RateControl::ConstantQp(settings.qp.map_or_else(|| hevc_qp(meta, settings), |qp| qp as i32));
8543 cfg.timing = Some((fps_den, fps_num));8562 cfg.timing = Some((fps_den, fps_num));
8544 cfg.video_signal_type = Some(video_signal_type(colour));8563 cfg.video_signal_type = Some(video_signal_type(colour));
8545 apply_hdr(&mut cfg, settings);8564 apply_hdr(&mut cfg, settings);
@@ -8706,14 +8725,9 @@ impl Enc {
8706 collect_av1(context, ready)?;8725 collect_av1(context, ready)?;
8707 Ok(pop_av1(ready, au))8726 Ok(pop_av1(ready, au))
8708 }8727 }
8709- // Every unit this seat hands back is an IDR carrying its own8728+ Self::HevcHw(hw, intra) => Ok(hw
8710- // parameter sets (the plugin codes HEVC intra-only), so every one of8729+ .encode(y, u, v, width, height, *intra)?
8711- // them is a sync point -- said as a constant rather than parsed back8730+ .map(|au| (au, hevc_irap(au)))),
8712- // out of the bitstream, because it is this encoder's configuration
8713- // and not a driver's choice.
8714- Self::HevcHw(hw) => Ok(hw
8715- .encode(y, u, v, width, height, true)?
8716- .map(|au| (au, true))),
8717 Self::Hevc(hevc) => {8731 Self::Hevc(hevc) => {
8718 // The display-size planes are kept as they came: `ec-h265`8732 // The display-size planes are kept as they came: `ec-h265`
8719 // pads to its own coded grid and crops back through the SPS8733 // pads to its own coded grid and crops back through the SPS
@@ -8765,7 +8779,7 @@ impl Enc {
8765 /// ([`crate::hwproc`]), which is a round trip on its socket.8779 /// ([`crate::hwproc`]), which is a round trip on its socket.
8766 fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {8780 fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {
8767 match self {8781 match self {
8768- Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height),8782+ Self::Hw(hw) | Self::HevcHw(hw, _) => hw.dma_want(meta.width, meta.height),
8769 _ => None,8783 _ => None,
8770 }8784 }
8771 }8785 }
@@ -8784,8 +8798,7 @@ impl Enc {
8784 fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> {8798 fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> {
8785 match self {8799 match self {
8786 Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))),8800 Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))),
8787- // Every picture an IDR here, exactly as in [`Enc::encode`].8801+ Self::HevcHw(hw, intra) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))),
8788- Self::HevcHw(hw) => Ok(hw.encode_dma(dma, true)?.map(|au| (au, true))),
8789 // Unreachable through [`Enc::dma_want`], which is the only thing8802 // Unreachable through [`Enc::dma_want`], which is the only thing
8790 // that puts a span's decoder on this path.8803 // that puts a span's decoder on this path.
8791 _ => Err("this encoder takes pictures as bytes, not as buffers".into()),8804 _ => Err("this encoder takes pictures as bytes, not as buffers".into()),
@@ -8826,7 +8839,7 @@ impl Enc {
8826 }8839 }
8827 Ok(pop_av1(ready, au))8840 Ok(pop_av1(ready, au))
8828 }8841 }
8829- Self::HevcHw(hw) => Ok(hw.drain()?.map(|au| (au, true))),8842+ Self::HevcHw(hw, _) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))),
8830 // The tail batch: fewer frames than lanes, coded on as many8843 // The tail batch: fewer frames than lanes, coded on as many
8831 // encoders as there are frames left.8844 // encoders as there are frames left.
8832 Self::Hevc(hevc) => {8845 Self::Hevc(hevc) => {
@@ -8931,12 +8944,13 @@ impl Enc {
8931 let keyint = hevc_gop_keyint(meta.frame_rate);8944 let keyint = hevc_gop_keyint(meta.frame_rate);
8932 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);8945 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);
8933 cfg.bit_depth = if ten_bit { 10 } else { 8 };8946 cfg.bit_depth = if ten_bit { 10 } else { 8 };
8934- cfg.rate_control = match settings.bitrate {8947+ cfg.rate_control = match (settings.qp, settings.bitrate) {
8935- Some(_) => RateControl::Bitrate {8948+ (Some(qp), _) => RateControl::ConstantQp(qp as i32),
8949+ (None, Some(_)) => RateControl::Bitrate {
8936 kbps: (bitrate_of(meta, settings) / 1000).max(1) as u32,8950 kbps: (bitrate_of(meta, settings) / 1000).max(1) as u32,
8937 fps: meta.frame_rate,8951 fps: meta.frame_rate,
8938 },8952 },
8939- None => RateControl::ConstantQp(HEVC_GOP_QP),8953+ (None, None) => RateControl::ConstantQp(HEVC_GOP_QP),
8940 };8954 };
8941 cfg.keyint = keyint;8955 cfg.keyint = keyint;
8942 cfg.threads = ec_h265::encoder::default_threads();8956 cfg.threads = ec_h265::encoder::default_threads();
@@ -9000,9 +9014,10 @@ pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<St
9000 return None;9014 return None;
9001 }9015 }
9002 if settings.intra_only {9016 if settings.intra_only {
9003- return Some(match settings.bitrate {9017+ return Some(match (settings.qp, settings.bitrate) {
9004- Some(_) => "intra-only".to_string(),9018+ (Some(qp), _) => format!("intra-only, constant QP {qp}"),
9005- None => format!(9019+ (None, Some(_)) => "intra-only".to_string(),
9020+ (None, None) => format!(
9006 "intra-only, constant quality QP {} on the software seat (the GPU seat codes at the automatic rate); pass bitrate_kbps for a fixed rate",9021 "intra-only, constant quality QP {} on the software seat (the GPU seat codes at the automatic rate); pass bitrate_kbps for a fixed rate",
9007 hevc_qp(meta, settings)9022 hevc_qp(meta, settings)
9008 ),9023 ),
@@ -9014,9 +9029,10 @@ pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<St
9014 } else {9029 } else {
9015 format!("{seconds:.2} s")9030 format!("{seconds:.2} s")
9016 };9031 };
9017- let rate = match settings.bitrate {9032+ let rate = match (settings.qp, settings.bitrate) {
9018- Some(_) => rate_words(bitrate_of(meta, settings) / 1000),9033+ (Some(qp), _) => format!("constant QP {qp}"),
9019- None => format!("constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"),9034+ (None, Some(_)) => rate_words(bitrate_of(meta, settings) / 1000),
9035+ (None, None) => format!("constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"),
9020 };9036 };
9021 Some(format!("I+P GOP ({every} keyframes), {rate}"))9037 Some(format!("I+P GOP ({every} keyframes), {rate}"))
9022 }9038 }
@@ -9028,6 +9044,9 @@ pub fn av1_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<Str
9028 if !settings.format.is_av1() {9044 if !settings.format.is_av1() {
9029 return None;9045 return None;
9030 }9046 }
9047+ if let Some(qp) = settings.qp {
9048+ return Some(format!("constant QP {qp}"));
9049+ }
9031 let rate = rate_words(bitrate_of(meta, settings) / 1000);9050 let rate = rate_words(bitrate_of(meta, settings) / 1000);
9032 Some(match settings.bitrate {9051 Some(match settings.bitrate {
9033 Some(_) => format!("average bitrate {rate}"),9052 Some(_) => format!("average bitrate {rate}"),
crates/engine/src/hw.rsmodified+26 -13
@@ -24,8 +24,8 @@ use std::sync::OnceLock;
24 24
25 use crate::colorspace::ColorDescription;25 use crate::colorspace::ColorDescription;
26 use crate::hwproc::{26 use crate::hwproc::{
27- DMA_BODY, HW_LOST, K_DMA, K_PIXELS, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, Shm, T_NEXT,27+ DMA_BODY, HW_LOST, K_DMA, K_PIXELS, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, SeatRate, Shm,
28- T_NEXT_DMA, T_SEEK, recv_reply, send_msg, spawn_child,28+ T_NEXT, T_NEXT_DMA, T_SEEK, recv_reply, send_msg, spawn_child,
29 };29 };
30 30
31 #[cfg(test)]31 #[cfg(test)]
@@ -491,18 +491,18 @@ pub struct HwEncoder(Remote);
491 491
492 impl HwEncoder {492 impl HwEncoder {
493 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded493 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
494- /// at a constant `bitrate` bits per second. `None` whenever hardware encode494+ /// at a constant `rate` (a bitrate or a quantiser). `None` whenever hardware encode
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, bitrate: u64) -> Option<Self> {498+ pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option<Self> {
499 Self::seated(499 Self::seated(
500 Seat::H264,500 Seat::H264,
501 width,501 width,
502 height,502 height,
503 fps_num,503 fps_num,
504 fps_den,504 fps_den,
505- bitrate,505+ rate,
506 ColorDescription::default(),506 ColorDescription::default(),
507 )507 )
508 }508 }
@@ -512,14 +512,14 @@ impl HwEncoder {
512 /// [`crate::proxy`] codes a stand-in with. `None` on a child that cannot512 /// [`crate::proxy`] codes a stand-in with. `None` on a child that cannot
513 /// make that seat, and the caller must then take the software encoder rather513 /// make that seat, and the caller must then take the software encoder rather
514 /// than the ordinary hardware seat.514 /// than the ordinary hardware seat.
515- pub fn open_intra(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {515+ pub fn open_intra(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option<Self> {
516 Self::seated(516 Self::seated(
517 Seat::Intra,517 Seat::Intra,
518 width,518 width,
519 height,519 height,
520 fps_num,520 fps_num,
521 fps_den,521 fps_den,
522- bitrate,522+ rate,
523 ColorDescription::default(),523 ColorDescription::default(),
524 )524 )
525 }525 }
@@ -527,14 +527,14 @@ impl HwEncoder {
527 /// The same, coding AV1 instead. `None` on a child or a GPU with no AV1527 /// 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 without528 /// encoder, and the caller's software AV1 encoder takes the export without
529 /// saying anything about it.529 /// saying anything about it.
530- pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {530+ pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option<Self> {
531 Self::seated(531 Self::seated(
532 Seat::Av1,532 Seat::Av1,
533 width,533 width,
534 height,534 height,
535 fps_num,535 fps_num,
536 fps_den,536 fps_den,
537- bitrate,537+ rate,
538 ColorDescription::default(),538 ColorDescription::default(),
539 )539 )
540 }540 }
@@ -547,10 +547,23 @@ impl HwEncoder {
547 height: u32,547 height: u32,
548 fps_num: u32,548 fps_num: u32,
549 fps_den: u32,549 fps_den: u32,
550- bitrate: u64,550+ rate: SeatRate,
551 colour: ColorDescription,551 colour: ColorDescription,
552 ) -> Option<Self> {552 ) -> Option<Self> {
553- Self::seated(Seat::Hevc, width, height, fps_num, fps_den, bitrate, colour)553+ Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour)
554+ }
555+
556+ /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`]
557+ /// is for H.264.
558+ pub fn open_hevc_intra(
559+ width: u32,
560+ height: u32,
561+ fps_num: u32,
562+ fps_den: u32,
563+ rate: SeatRate,
564+ colour: ColorDescription,
565+ ) -> Option<Self> {
566+ Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour)
554 }567 }
555 568
556 fn seated(569 fn seated(
@@ -559,7 +572,7 @@ impl HwEncoder {
559 height: u32,572 height: u32,
560 fps_num: u32,573 fps_num: u32,
561 fps_den: u32,574 fps_den: u32,
562- bitrate: u64,575+ rate: SeatRate,
563 colour: ColorDescription,576 colour: ColorDescription,
564 ) -> Option<Self> {577 ) -> Option<Self> {
565 let open = Open {578 let open = Open {
@@ -568,7 +581,7 @@ impl HwEncoder {
568 height,581 height,
569 fps_num,582 fps_num,
570 fps_den,583 fps_den,
571- bitrate,584+ rate,
572 colour,585 colour,
573 };586 };
574 // No child binary beside the executable means no hardware seat at all:587 // No child binary beside the executable means no hardware seat at all:
crates/engine/src/hwproc.rsmodified+28 -6
@@ -88,6 +88,7 @@ pub enum Seat {
88 Intra,88 Intra,
89 Av1,89 Av1,
90 Hevc,90 Hevc,
91+ HevcIntra,
91 }92 }
92 93
93 impl Seat {94 impl Seat {
@@ -97,6 +98,7 @@ impl Seat {
97 Self::Intra => 1,98 Self::Intra => 1,
98 Self::Av1 => 2,99 Self::Av1 => 2,
99 Self::Hevc => 3,100 Self::Hevc => 3,
101+ Self::HevcIntra => 4,
100 }102 }
101 }103 }
102 104
@@ -106,11 +108,20 @@ impl Seat {
106 1 => Self::Intra,108 1 => Self::Intra,
107 2 => Self::Av1,109 2 => Self::Av1,
108 3 => Self::Hevc,110 3 => Self::Hevc,
111+ 4 => Self::HevcIntra,
109 _ => return None,112 _ => return None,
110 })113 })
111 }114 }
112 }115 }
113 116
117+/// How the encode seat spends bits: a constant bitrate in bits per second, or a
118+/// constant quantiser (H.264/HEVC 0..51, AV1 0..255 on the seat's own scale).
119+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120+pub enum SeatRate {
121+ Bitrate(u64),
122+ ConstantQp(u32),
123+}
124+
114 /// Everything an open needs, in one place because it travels as argv and comes125 /// Everything an open needs, in one place because it travels as argv and comes
115 /// back as a struct on the other side.126 /// back as a struct on the other side.
116 #[derive(Clone, Copy)]127 #[derive(Clone, Copy)]
@@ -120,7 +131,7 @@ pub struct Open {
120 pub height: u32,131 pub height: u32,
121 pub fps_num: u32,132 pub fps_num: u32,
122 pub fps_den: u32,133 pub fps_den: u32,
123- pub bitrate: u64,134+ pub rate: SeatRate,
124 /// 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
125 /// takes one; the others ignore it.136 /// takes one; the others ignore it.
126 pub colour: ColorDescription,137 pub colour: ColorDescription,
@@ -152,7 +163,10 @@ impl Open {
152 ]163 ]
153 .iter()164 .iter()
154 .map(u32::to_string)165 .map(u32::to_string)
155- .chain(std::iter::once(self.bitrate.to_string()))166+ .chain(match self.rate {
167+ SeatRate::Bitrate(bps) => [0, bps],
168+ SeatRate::ConstantQp(qp) => [1, u64::from(qp)],
169+ }.map(|v| v.to_string()))
156 .collect()170 .collect()
157 }171 }
158 172
@@ -165,7 +179,14 @@ impl Open {
165 height: n(2)?,179 height: n(2)?,
166 fps_num: n(3)?,180 fps_num: n(3)?,
167 fps_den: n(4)?,181 fps_den: n(4)?,
168- bitrate: args.get(8)?.parse().ok()?,182+ rate: {
183+ let value = args.get(9)?.parse::<u64>().ok()?;
184+ match n(8)? {
185+ 0 => SeatRate::Bitrate(value),
186+ 1 => SeatRate::ConstantQp(u32::try_from(value).ok()?),
187+ _ => return None,
188+ }
189+ },
169 colour: ColorDescription {190 colour: ColorDescription {
170 matrix: match n(5)? {191 matrix: match n(5)? {
171 0 => Matrix::Bt709,192 0 => Matrix::Bt709,
@@ -783,7 +804,7 @@ mod tests {
783 height: 1080,804 height: 1080,
784 fps_num: 30000,805 fps_num: 30000,
785 fps_den: 1001,806 fps_den: 1001,
786- bitrate: 12_345_678,807+ rate: SeatRate::Bitrate(12_345_678),
787 colour: ColorDescription {808 colour: ColorDescription {
788 matrix: Matrix::Bt2020Ncl,809 matrix: Matrix::Bt2020Ncl,
789 transfer: Transfer::Pq,810 transfer: Transfer::Pq,
@@ -793,9 +814,10 @@ mod tests {
793 let back = Open::from_argv(&open.argv()).expect("parse");814 let back = Open::from_argv(&open.argv()).expect("parse");
794 assert!(back.seat == Seat::Hevc);815 assert!(back.seat == Seat::Hevc);
795 assert_eq!(816 assert_eq!(
796- (back.width, back.height, back.fps_num, back.fps_den, back.bitrate),817+ (back.width, back.height, back.fps_num, back.fps_den),
797- (1920, 1080, 30000, 1001, 12_345_678)818+ (1920, 1080, 30000, 1001)
798 );819 );
820+ assert!(back.rate == SeatRate::Bitrate(12_345_678));
799 assert_eq!(back.colour, open.colour);821 assert_eq!(back.colour, open.colour);
800 assert_eq!(back.frame_bytes(), 1920 * 1080 * 3 / 2);822 assert_eq!(back.frame_bytes(), 1920 * 1080 * 3 / 2);
801 }823 }
crates/engine/tests/export.rsmodified+4 -3
@@ -35,6 +35,7 @@ use ec_core::{Packet, TimeBase};
35 use ec_h264::H264Decoder;35 use ec_h264::H264Decoder;
36 use engine::export::ExportSettings;36 use engine::export::ExportSettings;
37 use engine::hw::HwEncoder;37 use engine::hw::HwEncoder;
38+use engine::hwproc::SeatRate;
38 use engine::mux::{parameter_sets, AudioParams, Mp4Muxer, VideoParams};39 use engine::mux::{parameter_sets, AudioParams, Mp4Muxer, VideoParams};
39 use engine::project::{Lane, Source, Speed};40 use engine::project::{Lane, Source, Speed};
40 use engine::scale::FitPolicy;41 use engine::scale::FitPolicy;
@@ -771,7 +772,7 @@ fn exports_audio_alongside_the_video() {
771 fn hardware_access_units_repack_into_mp4() {772 fn hardware_access_units_repack_into_mp4() {
772 let (w, h) = (640u32, 480u32);773 let (w, h) = (640u32, 480u32);
773 let mut encoder =774 let mut encoder =
774- HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver");775+ HwEncoder::open(w, h, 30, 1, SeatRate::Bitrate(4_000_000)).expect("no hardware encode plugin/driver");
775 let out = out_path("hwmux");776 let out = out_path("hwmux");
776 let mut muxer: Option<Mp4Muxer> = None;777 let mut muxer: Option<Mp4Muxer> = None;
777 let mut written = 0;778 let mut written = 0;
@@ -1918,7 +1919,7 @@ fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() {
1918 // 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.
1919 injected_with(None, Some("10"), None, || {1920 injected_with(None, Some("10"), None, || {
1920 let mut encoder =1921 let mut encoder =
1921- HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened");1922+ HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000)).expect("the stand-in seat opened");
1922 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);
1923 for frame in 0..10 {1924 for frame in 0..10 {
1924 assert!(1925 assert!(
@@ -2057,7 +2058,7 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() {
2057 let (width, height) = (320u32, 240u32);2058 let (width, height) = (320u32, 240u32);
2058 injected(Some("1"), None, || {2059 injected(Some("1"), None, || {
2059 let mut encoder =2060 let mut encoder =
2060- HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened");2061+ HwEncoder::open(width, height, 30, 1, SeatRate::Bitrate(1_000_000)).expect("the stand-in seat opened");
2061 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);
2062 assert!(2063 assert!(
2063 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+5 -4
@@ -19,6 +19,7 @@ mod hwchild;
19 use std::time::{Duration, Instant};19 use std::time::{Duration, Instant};
20 20
21 use engine::hw::{HwEncoder, HwPicture, HwSession};21 use engine::hw::{HwEncoder, HwPicture, HwSession};
22+use engine::hwproc::SeatRate;
22 use ec_core::registry::{CodecId, CodecParameters, Decoder as _};23 use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
23 use ec_core::{Packet, TimeBase};24 use ec_core::{Packet, TimeBase};
24 use ec_h264::H264Decoder;25 use ec_h264::H264Decoder;
@@ -44,7 +45,7 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<
44 /// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus45 /// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus
45 /// the number of access units the plugin handed back.46 /// the number of access units the plugin handed back.
46 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)> {
47- let mut encoder = HwEncoder::open(width, height, FPS, 1, BITRATE)?;48+ let mut encoder = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE))?;
48 let mut stream = Vec::new();49 let mut stream = Vec::new();
49 let mut units = 0;50 let mut units = 0;
50 // Timed around the plugin call only: building the synthetic picture is not51 // Timed around the plugin call only: building the synthetic picture is not
@@ -248,7 +249,7 @@ fn a_decoded_buffer_is_encoded_without_ever_being_read_back() {
248 let asset =249 let asset =
249 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");
250 let (width, height) = (1280u32, 720u32);251 let (width, height) = (1280u32, 720u32);
251- let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, BITRATE) else {252+ let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, SeatRate::Bitrate(BITRATE)) else {
252 println!("no hardware encoder here -- skipping");253 println!("no hardware encoder here -- skipping");
253 return;254 return;
254 };255 };
@@ -366,13 +367,13 @@ fn decode_and_encode_load_independently() {
366 let asset =367 let asset =
367 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");
368 assert!(369 assert!(
369- HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some(),370+ HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE)).is_some(),
370 "encode table"371 "encode table"
371 );372 );
372 assert!(HwSession::open(&asset).is_some(), "decode table");373 assert!(HwSession::open(&asset).is_some(), "decode table");
373 // Order reversed: neither table's `OnceLock` may have primed the other.374 // Order reversed: neither table's `OnceLock` may have primed the other.
374 assert!(HwSession::open(&asset).is_some());375 assert!(HwSession::open(&asset).is_some());
375- assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some());376+ assert!(HwEncoder::open(640, 480, FPS, 1, SeatRate::Bitrate(BITRATE)).is_some());
376 }377 }
377 378
378 /// 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/engine/tests/it/backends.rsmodified+1 -8
@@ -214,15 +214,8 @@ fn the_planned_seat_follows_the_size_and_the_pin() {
214 );214 );
215 std::thread::sleep(Duration::from_millis(10));215 std::thread::sleep(Duration::from_millis(10));
216 };216 };
217- // An I+P HEVC export is refused for a different reason: the GPU
218- // has an HEVC seat, and it codes intra pictures only.
219- let intra_only_refusal = matches!(
220- settings.format,
221- engine::export::Format::Hevc | engine::export::Format::HevcMp4
222- ) && !settings.intra_only;
223 assert!(217 assert!(
224- err.contains("no VA-API seat")218+ err.contains("no VA-API seat"),
225- || (intra_only_refusal && err.contains("codes intra pictures only")),
226 "{ext} {width}x{height}: the refusal names the missing seat, got {err}"219 "{ext} {width}x{height}: the refusal names the missing seat, got {err}"
227 );220 );
228 assert!(221 assert!(
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?, 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?, 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. audio_kbps: 128, 192, 256 or 320.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.
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+62 -10
@@ -3,7 +3,7 @@ use std::path::{Path, PathBuf};
3 use std::time::Instant;3 use std::time::Instant;
4 4
5 use engine::demux::Demuxer;5 use engine::demux::Demuxer;
6-use engine::export::{caption_title_clash, chroma_reduction_words, fit_picture_clips, planned_seats, planned_tone, EncoderSeat, ExportSettings, FitOutcome, Format, HdrOutput, HdrTransfer, GifSettings, HevcSpeed, ProResProfile, AUDIO_KBPS};6+use engine::export::{caption_title_clash, chroma_reduction_words, fit_picture_clips, planned_seats, planned_tone, EncoderSeat, NO_HW_SEAT, ExportSettings, FitOutcome, Format, HdrOutput, HdrTransfer, GifSettings, HevcSpeed, ProResProfile, AAC_MAX_KBPS, AUDIO_KBPS};
7 use engine::project::LaneKind;7 use engine::project::LaneKind;
8 use engine::scale::FitPolicy;8 use engine::scale::FitPolicy;
9 use engine::captionanim::{CaptionAnim, CaptionStyle, MAX_WORDS_PER_LINE};9 use engine::captionanim::{CaptionAnim, CaptionStyle, MAX_WORDS_PER_LINE};
@@ -312,12 +312,18 @@ fn start_schema() -> Value {
312 "bitrate_kbps": {312 "bitrate_kbps": {
313 "type": "integer",313 "type": "integer",
314 "minimum": 1,314 "minimum": 1,
315- "description": "Video bitrate in kbps. Omitted: chosen from the picture size and frame rate. Ignored by audio-only formats."315+ "description": "Video bitrate in kbps. Omitted: chosen from the picture size and frame rate. Ignored by audio-only formats. Not with qp."
316+ },
317+ "qp": {
318+ "type": "integer",
319+ "minimum": 0,
320+ "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."
316 },322 },
317 "audio_kbps": {323 "audio_kbps": {
318 "type": "integer",324 "type": "integer",
319- "enum": [128, 192, 256, 320],325+ "enum": [128, 192, 256, 320, 384],
320- "description": "Sound bitrate in kbps. Refused where the sound's rate is not a choice (wav, flac, a timeline with no sound, and similar)."326+ "description": "Sound bitrate in kbps: 128, 192, 256 or 320, and 384 for AAC only (mp4, av1, av1-mp4, hevc, hevc-mp4, m4a). Refused where the sound's rate is not a choice (wav, flac, a timeline with no sound, and similar)."
321 },327 },
322 "seat": {328 "seat": {
323 "type": "string",329 "type": "string",
@@ -1132,6 +1138,8 @@ fn plain_video(format: Format, seat: &str) -> String {
1132 "hardware"1138 "hardware"
1133 } else if seat.starts_with("copy") {1139 } else if seat.starts_with("copy") {
1134 "copy"1140 "copy"
1141+ } else if seat == NO_HW_SEAT {
1142+ "no hardware"
1135 } else {1143 } else {
1136 "software"1144 "software"
1137 };1145 };
@@ -1533,12 +1541,35 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1533 Some(k) => Some(k.saturating_mul(1000)),1541 Some(k) => Some(k.saturating_mul(1000)),
1534 None => None,1542 None => None,
1535 };1543 };
1544+ let qp = match opt_u64(args, "qp") {
1545+ None => None,
1546+ Some(q) if q <= 51 => Some(q as u32),
1547+ Some(q) => return Reply::err(format!("qp {q} is not 0 to 51")),
1548+ };
1549+ if qp.is_some() && bitrate.is_some() {
1550+ return Reply::err("qp and bitrate_kbps together: qp fixes the quantiser and bitrate_kbps the rate, so pass one");
1551+ }
1552+ if qp.is_some() && sound_only {
1553+ return Reply::err("qp sets the picture's quantiser, and this export is the sound alone");
1554+ }
1555+ if qp.is_some() && !matches!(format, Format::Mp4 | Format::Av1 | Format::Av1Mp4 | Format::Hevc | Format::HevcMp4 | Format::Webm) {
1556+ return Reply::err(format!(
1557+ "qp sets the picture's quantiser: it needs an mp4, av1, av1-mp4, hevc, hevc-mp4 or webm export, not {}",
1558+ format_name(format)
1559+ ));
1560+ }
1561+ if qp.is_some() && format.is_av1() && seat != EncoderSeat::Hardware {
1562+ return Reply::err("qp for AV1 needs seat hardware: auto and software code AV1 in software, which refuses a constant QP");
1563+ }
1564+ 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");
1566+ }
1536 let audio_kbps = match opt_u64(args, "audio_kbps") {1567 let audio_kbps = match opt_u64(args, "audio_kbps") {
1537 None => None,1568 None => None,
1538 Some(k) => {1569 Some(k) => {
1539- let Some(k32) = u32::try_from(k).ok().filter(|v| AUDIO_KBPS.contains(v)) else {1570+ let Some(k32) = u32::try_from(k).ok().filter(|v| AUDIO_KBPS.contains(v) || *v == AAC_MAX_KBPS) else {
1540 return Reply::err(format!(1571 return Reply::err(format!(
1541- "audio_kbps {k} is not one of {}",1572+ "audio_kbps {k} is not one of {}, or {AAC_MAX_KBPS} for AAC",
1542 AUDIO_KBPS.map(|v| v.to_string()).join(", ")1573 AUDIO_KBPS.map(|v| v.to_string()).join(", ")
1543 ));1574 ));
1544 };1575 };
@@ -1548,6 +1579,12 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1548 format_name(format)1579 format_name(format)
1549 ));1580 ));
1550 }1581 }
1582+ if k32 == AAC_MAX_KBPS && !codes_aac(format) {
1583+ return Reply::err(format!(
1584+ "audio_kbps {k} is AAC only (mp4, av1, av1-mp4, hevc, hevc-mp4, m4a); {} codes at 320 at most",
1585+ format_name(format)
1586+ ));
1587+ }
1551 Some(k32)1588 Some(k32)
1552 }1589 }
1553 };1590 };
@@ -1560,7 +1597,7 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1560 };1597 };
1561 // The preset fills what the arguments left out; an explicit argument wins.1598 // The preset fills what the arguments left out; an explicit argument wins.
1562 let preset_settings = preset.map(|p| engine::export_presets::apply(p, ExportSettings::default()));1599 let preset_settings = preset.map(|p| engine::export_presets::apply(p, ExportSettings::default()));
1563- let bitrate = bitrate.or(preset_settings.as_ref().and_then(|a| a.bitrate));1600+ let bitrate = bitrate.or(preset_settings.as_ref().filter(|_| qp.is_none()).and_then(|a| a.bitrate));
1564 let audio_kbps = audio_kbps.or(preset_settings.as_ref().and_then(|a| a.audio_kbps));1601 let audio_kbps = audio_kbps.or(preset_settings.as_ref().and_then(|a| a.audio_kbps));
1565 let size = size.or(preset_settings.as_ref().and_then(|a| a.size));1602 let size = size.or(preset_settings.as_ref().and_then(|a| a.size));
1566 let video_bit_depth = video_bit_depth.or(preset_settings.as_ref().and_then(|a| a.video_bit_depth));1603 let video_bit_depth = video_bit_depth.or(preset_settings.as_ref().and_then(|a| a.video_bit_depth));
@@ -1685,6 +1722,7 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1685 let chapters_written = chapters.len();1722 let chapters_written = chapters.len();
1686 let settings = ExportSettings {1723 let settings = ExportSettings {
1687 bitrate,1724 bitrate,
1725+ qp,
1688 seat,1726 seat,
1689 format,1727 format,
1690 intra_only: opt_bool(args, "intra_only").unwrap_or(false),1728 intra_only: opt_bool(args, "intra_only").unwrap_or(false),
@@ -1806,13 +1844,20 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1806 ));1844 ));
1807 }1845 }
1808 // An HEVC or AV1 export says in one line which encoder codes it and at what rate or quality.1846 // An HEVC or AV1 export says in one line which encoder codes it and at what rate or quality.
1809- let seat = if picture.starts_with("HW") { "hardware" } else { "software" };1847+ let seat = match picture.as_str() {
1848+ p if p.starts_with("HW") => "hardware",
1849+ NO_HW_SEAT => "no hardware",
1850+ _ => "software",
1851+ };
1810 if let Some(mode) = &hevc_mode {1852 if let Some(mode) = &hevc_mode {
1811 text.push_str(&format!("\nHEVC: {seat} encoder, {mode}"));1853 text.push_str(&format!("\nHEVC: {seat} encoder, {mode}"));
1812 }1854 }
1813 if let Some(mode) = &av1_mode {1855 if let Some(mode) = &av1_mode {
1814 text.push_str(&format!("\nAV1: {seat} encoder, {mode}"));1856 text.push_str(&format!("\nAV1: {seat} encoder, {mode}"));
1815 }1857 }
1858+ if let (Some(q), false) = (qp, format.is_hevc() || format.is_av1()) {
1859+ text.push_str(&format!("\nH.264: {seat} encoder, constant QP {q}"));
1860+ }
1816 if !waiting { text.push_str("\nThe export keeps running while you do other things; if the client only closes this server's input it finishes before the server exits, but if the server is stopped by a signal (as most clients do when they quit) it is cancelled and its partial file removed — poll export_status until it finishes."); }1861 if !waiting { text.push_str("\nThe export keeps running while you do other things; if the client only closes this server's input it finishes before the server exits, but if the server is stopped by a signal (as most clients do when they quit) it is cancelled and its partial file removed — poll export_status until it finishes."); }
1817 if !sub_note.is_empty() {1862 if !sub_note.is_empty() {
1818 text.push('\n');1863 text.push('\n');
@@ -1852,6 +1897,11 @@ fn export_start(srv: &mut Server, args: &Value) -> Reply {
1852 }))1897 }))
1853 }1898 }
1854 1899
1900+/// Whether the format's sound is AAC, the only one that codes above 320 kbps.
1901+fn codes_aac(format: Format) -> bool {
1902+ matches!(format, Format::Mp4 | Format::Av1 | Format::Av1Mp4 | Format::Hevc | Format::HevcMp4 | Format::M4a)
1903+}
1904+
1855 /// Whether any picture source the timeline reads is 10-bit: the same test the engine's AV11905 /// Whether any picture source the timeline reads is 10-bit: the same test the engine's AV1
1856 /// seat makes ([`engine::export`]'s `av1_ten_bit`). Still images have no bit depth to read.1906 /// seat makes ([`engine::export`]'s `av1_ten_bit`). Still images have no bit depth to read.
1857 fn source_ten_bit(s: &PlaybackSession) -> bool {1907 fn source_ten_bit(s: &PlaybackSession) -> bool {
@@ -2348,7 +2398,8 @@ mod tests {
2348 }));2398 }));
2349 assert!(!at_rate.is_error, "{}", at_rate.text);2399 assert!(!at_rate.is_error, "{}", at_rate.text);
2350 assert!(2400 assert!(
2351- at_rate.text.contains("\nHEVC: software encoder, I+P GOP (1 s keyframes), 4 Mb/s"),2401+ at_rate.text.contains("\nHEVC: software encoder, I+P GOP (1 s keyframes), 4 Mb/s")
2402+ || at_rate.text.contains("\nHEVC: hardware encoder, I+P GOP (1 s keyframes), 4 Mb/s"),
2352 "the I+P line names the seat, the GOP and the rate: {}",2403 "the I+P line names the seat, the GOP and the rate: {}",
2353 at_rate.text2404 at_rate.text
2354 );2405 );
@@ -2358,7 +2409,8 @@ mod tests {
2358 }));2409 }));
2359 assert!(!quality.is_error, "{}", quality.text);2410 assert!(!quality.is_error, "{}", quality.text);
2360 assert!(2411 assert!(
2361- quality.text.contains("\nHEVC: software encoder, I+P GOP (1 s keyframes), constant quality"),2412+ quality.text.contains("\nHEVC: software encoder, I+P GOP (1 s keyframes), constant quality")
2413+ || quality.text.contains("\nHEVC: hardware encoder, I+P GOP (1 s keyframes), constant quality"),
2362 "the automatic row says constant quality: {}",2414 "the automatic row says constant quality: {}",
2363 quality.text2415 quality.text
2364 );2416 );