Skip to content

Commit 003623b

Browse files
committed
Implement support for encoding HDR10+ from JSON metadata file
1 parent 90fdd3d commit 003623b

File tree

8 files changed

+142
-2
lines changed

8 files changed

+142
-2
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.13.0"
110110
av1-grain = { version = "0.2.0", features = ["serialize"] }
111111
serde-big-array = { version = "0.4.1", optional = true }
112+
hdr10plus = { version = "2.0.0", features = ["json"] }
112113

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

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.
@@ -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 payloads are expected to follow the specification
98+
/// defined at https://aomediacodec.github.io/av1-hdr10plus.
99+
pub hdr10plus_payloads: Option<BTreeMap<u64, Vec<u8>>>,
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/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) {
@@ -1725,4 +1739,51 @@ impl<T: Pixel> ContextInner<T> {
17251739
(prev_keyframe_nframes, prev_keyframe_ntus)
17261740
}
17271741
}
1742+
1743+
/// Updates the T.35 metadata to be added to the frame.
1744+
/// The existing T.35 array may come from `FrameParameters`.
1745+
///
1746+
/// Added from [`EncoderConfig`]:
1747+
/// - HDR10+, ST2094-40 in `hdr10plus_payloads`.
1748+
///
1749+
/// Returns an `Option`, where `None` means the T.35 metadata is unchanged.
1750+
/// Otherwise, the updated T.35 metadata is returned.
1751+
fn get_maybe_updated_t35_metadata(
1752+
&self, input_frameno: u64, maybe_existing_t35_metadata: Option<&[T35]>,
1753+
) -> Option<Vec<T35>> {
1754+
let hdr10plus_payload = self
1755+
.config
1756+
.hdr10plus_payloads
1757+
.as_ref()
1758+
.and_then(|list| list.get(&input_frameno));
1759+
1760+
let update_t35_metadata = hdr10plus_payload.is_some();
1761+
1762+
let mut new_t35_metadata = if update_t35_metadata {
1763+
Some(
1764+
maybe_existing_t35_metadata.map_or_else(Vec::new, |t35| t35.to_vec()),
1765+
)
1766+
} else {
1767+
None
1768+
};
1769+
1770+
if let Some(list) = new_t35_metadata.as_mut() {
1771+
// HDR10+, ST2094-40
1772+
if let Some(payload) = hdr10plus_payload {
1773+
let has_existing_hdr10plus_meta = list.iter().any(|t35| {
1774+
t35.country_code == 0xB5 && t35.data.starts_with(ST2094_40_PREFIX)
1775+
});
1776+
1777+
if !has_existing_hdr10plus_meta {
1778+
list.push(T35 {
1779+
country_code: 0xB5,
1780+
country_code_extension_byte: 0x00,
1781+
data: payload.clone().into_boxed_slice(),
1782+
});
1783+
}
1784+
}
1785+
}
1786+
1787+
new_t35_metadata
1788+
}
17281789
}

src/api/test.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2129,6 +2129,7 @@ fn log_q_exp_overflow() {
21292129
bitrate: 1,
21302130
tune: Tune::Psychovisual,
21312131
film_grain_params: None,
2132+
hdr10plus_payloads: None,
21322133
tile_cols: 0,
21332134
tile_rows: 0,
21342135
tiles: 0,
@@ -2206,6 +2207,7 @@ fn guess_frame_subtypes_assert() {
22062207
bitrate: 16384,
22072208
tune: Tune::Psychovisual,
22082209
film_grain_params: None,
2210+
hdr10plus_payloads: None,
22092211
tile_cols: 0,
22102212
tile_rows: 0,
22112213
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

+37
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,34 @@ 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, Vec<u8>> = 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+
.ok()
708+
})
709+
.zip(0u64..)
710+
.map(|(payload, frame_no)| (frame_no, payload))
711+
.collect();
712+
713+
if !payloads.is_empty() {
714+
cfg.hdr10plus_payloads = Some(payloads);
715+
}
716+
}
717+
681718
if let Some(frame_rate) = matches.frame_rate {
682719
cfg.time_base = Rational::new(matches.time_scale, frame_rate);
683720
}

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)