Skip to content

Commit bb25f47

Browse files
committed
Implement support for encoding HDR10+ from JSON metadata file
1 parent 73f0b6e commit bb25f47

File tree

6 files changed

+119
-2
lines changed

6 files changed

+119
-2
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ new_debug_unreachable = "1.0.4"
105105
once_cell = "1.13.0"
106106
av1-grain = { version = "0.1.1", features = ["serialize"] }
107107
serde-big-array = { version = "0.4.1", optional = true }
108+
hdr10plus = { version = "1.1.1", features = ["json"] }
108109

109110
[dependencies.image]
110111
version = "0.23"

src/api/config/encoder.rs

+7
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ 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.
@@ -85,6 +86,11 @@ pub struct EncoderConfig {
8586
pub tune: Tune,
8687
/// Parameters for grain synthesis.
8788
pub film_grain_params: Option<Vec<GrainTableSegment>>,
89+
/// HDR10+, ST2094-40 T.35 metadata payload map, by input frame index.
90+
///
91+
/// The payloads are expected to follow the specification
92+
/// defined at https://aomediacodec.github.io/av1-hdr10plus.
93+
pub hdr10plus_payloads: Option<BTreeMap<u64, Vec<u8>>>,
8894
/// Number of tiles horizontally. Must be a power of two.
8995
///
9096
/// Overridden by [`tiles`], if present.
@@ -162,6 +168,7 @@ impl EncoderConfig {
162168
bitrate: 0,
163169
tune: Tune::default(),
164170
film_grain_params: None,
171+
hdr10plus_payloads: None,
165172
tile_cols: 0,
166173
tile_rows: 0,
167174
tiles: 0,

src/api/internal.rs

+63-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
use crate::activity::ActivityMask;
1212
use crate::api::lookahead::*;
1313
use crate::api::{
14-
EncoderConfig, EncoderStatus, FrameType, Opaque, Packet, T35,
14+
EncoderConfig, EncoderStatus, FrameType, Opaque, Packet, ST2094_40_PREFIX,
15+
T35,
1516
};
1617
use crate::color::ChromaSampling::Cs400;
1718
use crate::cpu_features::CpuFeatureLevel;
@@ -349,14 +350,27 @@ impl<T: Pixel> ContextInner<T> {
349350
}
350351
self.frame_q.insert(input_frameno, frame);
351352

353+
// Update T.35 metadata from encoder config
354+
let maybe_updated_t35_metadata = self.get_maybe_updated_t35_metadata(
355+
input_frameno,
356+
params.as_ref().map(|params| params.t35_metadata.as_ref()),
357+
);
358+
352359
if let Some(params) = params {
353360
if params.frame_type_override == FrameTypeOverride::Key {
354361
self.keyframes_forced.insert(input_frameno);
355362
}
356363
if let Some(op) = params.opaque {
357364
self.opaque_q.insert(input_frameno, op);
358365
}
359-
self.t35_q.insert(input_frameno, params.t35_metadata);
366+
367+
if let Some(new_t35_metadata) = maybe_updated_t35_metadata {
368+
self.t35_q.insert(input_frameno, new_t35_metadata.into_boxed_slice());
369+
} else {
370+
self.t35_q.insert(input_frameno, params.t35_metadata);
371+
}
372+
} else if let Some(new_t35_metadata) = maybe_updated_t35_metadata {
373+
self.t35_q.insert(input_frameno, new_t35_metadata.into_boxed_slice());
360374
}
361375

362376
if !self.needs_more_frame_q_lookahead(self.next_lookahead_frame) {
@@ -1688,4 +1702,51 @@ impl<T: Pixel> ContextInner<T> {
16881702
(prev_keyframe_nframes, prev_keyframe_ntus)
16891703
}
16901704
}
1705+
1706+
/// Updates the T.35 metadata to be added to the frame.
1707+
/// The existing T.35 array may come from `FrameParameters`.
1708+
///
1709+
/// Added from [`EncoderConfig`]:
1710+
/// - HDR10+, ST2094-40 in `hdr10plus_payloads`.
1711+
///
1712+
/// Returns an `Option`, where `None` means the T.35 metadata is unchanged.
1713+
/// Otherwise, the updated T.35 metadata is returned.
1714+
fn get_maybe_updated_t35_metadata(
1715+
&self, input_frameno: u64, maybe_existing_t35_metadata: Option<&[T35]>,
1716+
) -> Option<Vec<T35>> {
1717+
let hdr10plus_payload = self
1718+
.config
1719+
.hdr10plus_payloads
1720+
.as_ref()
1721+
.and_then(|list| list.get(&input_frameno));
1722+
1723+
let update_t35_metadata = hdr10plus_payload.is_some();
1724+
1725+
let mut new_t35_metadata = if update_t35_metadata {
1726+
Some(
1727+
maybe_existing_t35_metadata.map_or_else(Vec::new, |t35| t35.to_vec()),
1728+
)
1729+
} else {
1730+
None
1731+
};
1732+
1733+
if let Some(list) = new_t35_metadata.as_mut() {
1734+
// HDR10+, ST2094-40
1735+
if let Some(payload) = hdr10plus_payload {
1736+
let has_existing_hdr10plus_meta = list.iter().any(|t35| {
1737+
t35.country_code == 0xB5 && t35.data.starts_with(ST2094_40_PREFIX)
1738+
});
1739+
1740+
if !has_existing_hdr10plus_meta {
1741+
list.push(T35 {
1742+
country_code: 0xB5,
1743+
country_code_extension_byte: 0x00,
1744+
data: payload.clone().into_boxed_slice(),
1745+
});
1746+
}
1747+
}
1748+
}
1749+
1750+
new_t35_metadata
1751+
}
16911752
}

src/api/test.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2128,6 +2128,7 @@ fn log_q_exp_overflow() {
21282128
bitrate: 1,
21292129
tune: Tune::Psychovisual,
21302130
film_grain_params: None,
2131+
hdr10plus_payloads: None,
21312132
tile_cols: 0,
21322133
tile_rows: 0,
21332134
tiles: 0,
@@ -2205,6 +2206,7 @@ fn guess_frame_subtypes_assert() {
22052206
bitrate: 16384,
22062207
tune: Tune::Psychovisual,
22072208
film_grain_params: None,
2209+
hdr10plus_payloads: None,
22082210
tile_cols: 0,
22092211
tile_rows: 0,
22102212
tiles: 0,

src/api/util.rs

+8
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 {

src/bin/common.rs

+38
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::*;
@@ -203,6 +204,14 @@ pub struct CliOptions {
203204
help_heading = "ENCODE SETTINGS"
204205
)]
205206
pub film_grain_table: Option<PathBuf>,
207+
/// Uses a HDR10+ metadata JSON file to add as T.35 metadata to the encode.
208+
#[clap(
209+
long,
210+
alias = "dhdr10-info",
211+
value_parser,
212+
help_heading = "ENCODE SETTINGS"
213+
)]
214+
pub hdr10plus_json: Option<PathBuf>,
206215

207216
/// Pixel range
208217
#[clap(long, value_parser, help_heading = "VIDEO METADATA")]
@@ -693,6 +702,35 @@ fn parse_config(matches: &CliOptions) -> Result<EncoderConfig, CliError> {
693702
}
694703
}
695704

705+
if let Some(json_file) = matches.hdr10plus_json.as_ref() {
706+
let contents = std::fs::read_to_string(json_file)
707+
.expect("Failed to read HDR10+ metadata file");
708+
let metadata_root =
709+
hdr10plus::metadata_json::MetadataJsonRoot::parse(&contents)
710+
.expect("Failed to parse HDR10+ metadata");
711+
712+
let payloads: BTreeMap<u64, Vec<u8>> = metadata_root
713+
.scene_info
714+
.iter()
715+
.filter_map(|meta| {
716+
hdr10plus::metadata::Hdr10PlusMetadata::try_from(meta)
717+
.and_then(|meta| meta.encode(true))
718+
.ok()
719+
.map(|mut bytes| {
720+
// Serialized with country code, which shouldn't be present
721+
bytes.remove(0);
722+
bytes
723+
})
724+
})
725+
.zip(0u64..)
726+
.map(|(payload, frame_no)| (frame_no, payload))
727+
.collect();
728+
729+
if !payloads.is_empty() {
730+
cfg.hdr10plus_payloads = Some(payloads);
731+
}
732+
}
733+
696734
if let Some(frame_rate) = matches.frame_rate {
697735
cfg.time_base = Rational::new(matches.time_scale, frame_rate);
698736
}

0 commit comments

Comments
 (0)