Skip to content

Commit d470cab

Browse files
committed
Implement support for encoding HDR10+ from JSON metadata file
1 parent f178e97 commit d470cab

File tree

8 files changed

+131
-11
lines changed

8 files changed

+131
-11
lines changed

Cargo.lock

+23
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ new_debug_unreachable = "1.0.4"
109109
once_cell = "1.17.1"
110110
av1-grain = { version = "0.2.0", features = ["serialize"] }
111111
serde-big-array = { version = "0.5.0", optional = true }
112+
hdr10plus = { version = "2.0.0", features = ["json"] }
112113

113114
[dependencies.image]
114115
version = "0.24.3"

src/api/config/encoder.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@
99

1010
use itertools::*;
1111

12-
use crate::api::color::*;
1312
use crate::api::config::GrainTableSegment;
13+
use crate::api::{color::*, T35};
1414
use crate::api::{Rational, SpeedSettings};
1515
use crate::encoder::Tune;
1616
use crate::serialize::{Deserialize, Serialize};
1717

18+
use std::collections::BTreeMap;
1819
use std::fmt;
1920

2021
// We add 1 to rdo_lookahead_frames in a bunch of places.
@@ -91,6 +92,11 @@ pub struct EncoderConfig {
9192
pub tune: Tune,
9293
/// Parameters for grain synthesis.
9394
pub film_grain_params: Option<Vec<GrainTableSegment>>,
95+
/// HDR10+, ST2094-40 T.35 metadata payload map, by input frame index.
96+
///
97+
/// The T.35 metadata is expected to follow the specification
98+
/// defined at https://aomediacodec.github.io/av1-hdr10plus.
99+
pub hdr10plus_payloads: Option<BTreeMap<u64, T35>>,
94100
/// Number of tiles horizontally. Must be a power of two.
95101
///
96102
/// Overridden by [`tiles`], if present.
@@ -167,6 +173,7 @@ impl EncoderConfig {
167173
bitrate: 0,
168174
tune: Tune::default(),
169175
film_grain_params: None,
176+
hdr10plus_payloads: None,
170177
tile_cols: 0,
171178
tile_rows: 0,
172179
tiles: 0,

src/api/test.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2127,6 +2127,7 @@ fn log_q_exp_overflow() {
21272127
bitrate: 1,
21282128
tune: Tune::Psychovisual,
21292129
film_grain_params: None,
2130+
hdr10plus_payloads: None,
21302131
tile_cols: 0,
21312132
tile_rows: 0,
21322133
tiles: 0,
@@ -2204,6 +2205,7 @@ fn guess_frame_subtypes_assert() {
22042205
bitrate: 16384,
22052206
tune: Tune::Psychovisual,
22062207
film_grain_params: None,
2208+
hdr10plus_payloads: None,
22072209
tile_cols: 0,
22082210
tile_rows: 0,
22092211
tiles: 0,

src/api/util.rs

+17
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,14 @@ impl fmt::Display for FrameType {
137137
}
138138
}
139139

140+
/// ST2094-40 T.35 metadata payload expected prefix.
141+
pub const ST2094_40_PREFIX: &[u8] = &[
142+
0x00, 0x03C, // Samsung Electronics America
143+
0x00, 0x01, // ST-2094-40
144+
0x04, // application_identifier = 4
145+
0x01, // application_mode = 1
146+
];
147+
140148
/// A single T.35 metadata packet.
141149
#[derive(Clone, Debug, Default)]
142150
pub struct T35 {
@@ -299,3 +307,12 @@ impl<T: Pixel> IntoFrame<T> for (Frame<T>, Option<FrameParameters>) {
299307
(Some(Arc::new(self.0)), self.1)
300308
}
301309
}
310+
311+
impl T35 {
312+
/// Whether the T.35 metadata is HDR10+ Metadata.
313+
///
314+
/// According to the [AV1 HDR10+ specification](https://aomediacodec.github.io/av1-hdr10plus).
315+
pub fn is_hdr10plus_metadata(&self) -> bool {
316+
self.country_code == 0xB5 && self.data.starts_with(ST2094_40_PREFIX)
317+
}
318+
}

src/bin/common.rs

+42
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use once_cell::sync::Lazy;
1717
use rav1e::prelude::*;
1818
use scan_fmt::scan_fmt;
1919

20+
use std::collections::BTreeMap;
2021
use std::fs::File;
2122
use std::io;
2223
use std::io::prelude::*;
@@ -194,6 +195,14 @@ pub struct CliOptions {
194195
help_heading = "ENCODE SETTINGS"
195196
)]
196197
pub film_grain_table: Option<PathBuf>,
198+
/// Uses a HDR10+ metadata JSON file to add as T.35 metadata to the encode.
199+
#[clap(
200+
long,
201+
alias = "dhdr10-info",
202+
value_parser,
203+
help_heading = "ENCODE SETTINGS"
204+
)]
205+
pub hdr10plus_json: Option<PathBuf>,
197206

198207
/// Pixel range
199208
#[clap(long, value_parser, help_heading = "VIDEO METADATA")]
@@ -678,6 +687,39 @@ fn parse_config(matches: &CliOptions) -> Result<EncoderConfig, CliError> {
678687
}
679688
}
680689

690+
if let Some(json_file) = matches.hdr10plus_json.as_ref() {
691+
let contents = std::fs::read_to_string(json_file)
692+
.expect("Failed to read HDR10+ metadata file");
693+
let metadata_root =
694+
hdr10plus::metadata_json::MetadataJsonRoot::parse(&contents)
695+
.expect("Failed to parse HDR10+ metadata");
696+
697+
let hdr10plus_enc_opts = hdr10plus::metadata::Hdr10PlusMetadataEncOpts {
698+
with_country_code: false,
699+
..Default::default()
700+
};
701+
let payloads: BTreeMap<u64, T35> = metadata_root
702+
.scene_info
703+
.iter()
704+
.filter_map(|meta| {
705+
hdr10plus::metadata::Hdr10PlusMetadata::try_from(meta)
706+
.and_then(|meta| meta.encode_with_opts(&hdr10plus_enc_opts))
707+
.map(|payload| T35 {
708+
country_code: 0xB5,
709+
country_code_extension_byte: 0x00,
710+
data: payload.into_boxed_slice(),
711+
})
712+
.ok()
713+
})
714+
.zip(0u64..)
715+
.map(|(payload, frame_no)| (frame_no, payload))
716+
.collect();
717+
718+
if !payloads.is_empty() {
719+
cfg.hdr10plus_payloads = Some(payloads);
720+
}
721+
}
722+
681723
if let Some(frame_rate) = matches.frame_rate {
682724
cfg.time_base = Rational::new(matches.time_scale, frame_rate);
683725
}

src/encoder.rs

+37-10
Original file line numberDiff line numberDiff line change
@@ -1287,6 +1287,19 @@ impl<T: Pixel> FrameInvariants<T> {
12871287
self.input_frameno * TIMESTAMP_BASE_UNIT * self.sequence.time_base.num
12881288
/ self.sequence.time_base.den
12891289
}
1290+
1291+
/// HDR10+ Metadata as T.35 metadata from [`EncoderConfig`]
1292+
pub fn hdr10plus_metadata(&self) -> Option<&T35> {
1293+
if !(self.show_frame || self.is_show_existing_frame()) {
1294+
return None;
1295+
}
1296+
1297+
self
1298+
.config
1299+
.hdr10plus_payloads
1300+
.as_ref()
1301+
.and_then(|payloads| payloads.get(&self.input_frameno))
1302+
}
12901303
}
12911304

12921305
impl<T: Pixel> fmt::Display for FrameInvariants<T> {
@@ -3682,11 +3695,14 @@ pub fn encode_show_existing_frame<T: Pixel>(
36823695
}
36833696

36843697
for t35 in fi.t35_metadata.iter() {
3685-
let mut t35_buf = Vec::new();
3686-
let mut t35_bw = BitWriter::endian(&mut t35_buf, BigEndian);
3687-
t35_bw.write_t35_metadata_obu(t35).unwrap();
3688-
packet.write_all(&t35_buf).unwrap();
3689-
t35_buf.clear();
3698+
write_t35_metadata_packet(&mut packet, t35);
3699+
}
3700+
3701+
// HDR10+ Metadata OBU from config
3702+
if let Some(t35) = fi.hdr10plus_metadata() {
3703+
if !fi.t35_metadata.iter().any(|t35| t35.is_hdr10plus_metadata()) {
3704+
write_t35_metadata_packet(&mut packet, t35);
3705+
}
36903706
}
36913707

36923708
let mut buf1 = Vec::new();
@@ -3762,11 +3778,14 @@ pub fn encode_frame<T: Pixel>(
37623778
}
37633779

37643780
for t35 in fi.t35_metadata.iter() {
3765-
let mut t35_buf = Vec::new();
3766-
let mut t35_bw = BitWriter::endian(&mut t35_buf, BigEndian);
3767-
t35_bw.write_t35_metadata_obu(t35).unwrap();
3768-
packet.write_all(&t35_buf).unwrap();
3769-
t35_buf.clear();
3781+
write_t35_metadata_packet(&mut packet, t35);
3782+
}
3783+
3784+
// HDR10+ Metadata OBU from config
3785+
if let Some(t35) = fi.hdr10plus_metadata() {
3786+
if !fi.t35_metadata.iter().any(|t35| t35.is_hdr10plus_metadata()) {
3787+
write_t35_metadata_packet(&mut packet, t35);
3788+
}
37703789
}
37713790

37723791
let mut buf1 = Vec::new();
@@ -3822,6 +3841,14 @@ pub fn update_rec_buffer<T: Pixel>(
38223841
}
38233842
}
38243843

3844+
fn write_t35_metadata_packet(packet: &mut Vec<u8>, t35: &T35) {
3845+
let mut t35_buf = Vec::new();
3846+
let mut t35_bw = BitWriter::endian(&mut t35_buf, BigEndian);
3847+
t35_bw.write_t35_metadata_obu(t35).unwrap();
3848+
packet.write_all(&t35_buf).unwrap();
3849+
t35_buf.clear();
3850+
}
3851+
38253852
#[cfg(test)]
38263853
mod test {
38273854
use super::*;

src/fuzzing.rs

+1
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@ impl Arbitrary<'_> for ArbitraryEncoder {
258258
switch_frame_interval: u.int_in_range(0..=3)?,
259259
tune: *u.choose(&[Tune::Psnr, Tune::Psychovisual])?,
260260
film_grain_params: None,
261+
hdr10plus_payloads: None,
261262
};
262263

263264
let frame_count =

0 commit comments

Comments
 (0)