use bytes::Bytes;
use scuffle_h265::SpsNALUnit;
use super::{Error, split::nal_unit_type};
use crate::Result;
use crate::catalog::hang::CatalogExt;
use crate::codec::annexb::NalIterator;
use crate::container::Frame;
use crate::container::jitter::Jitter;
pub struct Import<E: CatalogExt = ()> {
track: crate::container::Producer<crate::catalog::hang::Container>,
rendition: crate::catalog::VideoTrack<E>,
config: Option<hang::catalog::VideoConfig>,
last_sps: Option<Bytes>,
jitter: Jitter,
}
impl<E: CatalogExt> Import<E> {
pub fn new(track: moq_net::TrackProducer, catalog: crate::catalog::Producer<E>) -> Self {
let rendition = catalog.video_track(track.name());
Self {
track: catalog.media_producer(track, crate::catalog::hang::Container::Legacy),
rendition,
config: None,
last_sps: None,
jitter: Jitter::new(),
}
}
pub fn initialize(&mut self, buf: &[u8]) -> Result<()> {
let mut scan = Bytes::copy_from_slice(buf);
let mut nals = NalIterator::new(&mut scan);
while let Some(nal) = nals.next().transpose()? {
if is_sps(&nal) {
self.configure_from_sps(&nal)?;
}
}
if let Some(nal) = nals.flush()?
&& is_sps(&nal)
{
self.configure_from_sps(&nal)?;
}
Ok(())
}
pub fn name(&self) -> &str {
self.track.name()
}
pub fn demand(&self) -> moq_net::TrackDemand {
self.track.track().demand()
}
pub fn finish(&mut self) -> Result<()> {
self.track.finish()?;
Ok(())
}
pub fn seek(&mut self, sequence: u64) -> Result<()> {
self.track.seek(sequence)?;
Ok(())
}
pub fn observe_reorder(&mut self, reorder: crate::container::Timestamp) {
if let Some(jitter) = self.jitter.observe_reorder(reorder) {
self.rendition
.update(|c| c.jitter = moq_net::Time::try_from(jitter).ok());
}
}
fn configure_from_sps(&mut self, sps_nal: &Bytes) -> Result<()> {
if self.last_sps.as_ref() == Some(sps_nal) {
return Ok(());
}
let sps = SpsNALUnit::parse(&mut &sps_nal[..]).map_err(|_| Error::SpsParse)?;
let profile = &sps.rbsp.profile_tier_level.general_profile;
let vui_data = sps.rbsp.vui_parameters.as_ref().map(VuiData::new).unwrap_or_default();
let mut config = hang::catalog::VideoConfig::new(hang::catalog::H265 {
in_band: true, profile_space: profile.profile_space,
profile_idc: profile.profile_idc,
profile_compatibility_flags: profile.profile_compatibility_flag.bits().to_be_bytes(),
tier_flag: profile.tier_flag,
level_idc: profile.level_idc.ok_or(Error::MissingLevelIdc)?,
constraint_flags: super::pack_constraint_flags(profile),
});
config.coded_width = Some(sps.rbsp.cropped_width() as u32);
config.coded_height = Some(sps.rbsp.cropped_height() as u32);
config.framerate = vui_data.framerate;
config.display_ratio_width = vui_data.display_ratio_width;
config.display_ratio_height = vui_data.display_ratio_height;
config.container = hang::catalog::Container::Legacy;
self.last_sps = Some(sps_nal.clone());
if self.config.as_ref() == Some(&config) {
return Ok(());
}
tracing::debug!(name = ?self.track.name(), ?config, "starting track");
self.rendition.set(config.clone());
if let Some(jitter) = self.jitter.current() {
self.rendition
.update(|c| c.jitter = moq_net::Time::try_from(jitter).ok());
}
self.config = Some(config);
Ok(())
}
fn write_frames(&mut self, frames: impl IntoIterator<Item = Frame>) -> Result<()> {
for frame in frames {
if frame.keyframe
&& let Some(sps) = find_sps(&frame.payload)
{
self.configure_from_sps(&sps)?;
}
if frame.keyframe && self.config.is_none() {
return Err(Error::MissingSps.into());
}
let pts = frame.timestamp;
self.track.write(frame)?;
if let Some(jitter) = self.jitter.observe(pts) {
self.rendition
.update(|c| c.jitter = moq_net::Time::try_from(jitter).ok());
}
}
Ok(())
}
pub fn decode(&mut self, frames: impl IntoIterator<Item = Frame>) -> Result<()> {
self.write_frames(frames)
}
}
fn is_sps(nal: &[u8]) -> bool {
nal.first()
.is_some_and(|h| nal_unit_type(*h) == scuffle_h265::NALUnitType::SpsNut)
}
fn find_sps(payload: &[u8]) -> Option<Bytes> {
let mut buf = Bytes::copy_from_slice(payload);
let mut nals = NalIterator::new(&mut buf);
while let Some(Ok(nal)) = nals.next() {
if is_sps(&nal) {
return Some(nal);
}
}
nals.flush().ok().flatten().filter(|nal| is_sps(nal))
}
#[derive(Default)]
struct VuiData {
framerate: Option<f64>,
display_ratio_width: Option<u32>,
display_ratio_height: Option<u32>,
}
impl VuiData {
fn new(vui: &scuffle_h265::VuiParameters) -> Self {
let framerate = vui
.vui_timing_info
.as_ref()
.map(|t| t.time_scale.get() as f64 / t.num_units_in_tick.get() as f64);
let (display_ratio_width, display_ratio_height) = match &vui.aspect_ratio_info {
scuffle_h265::AspectRatioInfo::ExtendedSar { sar_width, sar_height } => {
(Some(*sar_width as u32), Some(*sar_height as u32))
}
scuffle_h265::AspectRatioInfo::Predefined(idc) => aspect_ratio_from_idc(*idc)
.map(|(w, h)| (Some(w), Some(h)))
.unwrap_or((None, None)),
};
VuiData {
framerate,
display_ratio_width,
display_ratio_height,
}
}
}
fn aspect_ratio_from_idc(idc: scuffle_h265::AspectRatioIdc) -> Option<(u32, u32)> {
match idc {
scuffle_h265::AspectRatioIdc::Unspecified => None,
scuffle_h265::AspectRatioIdc::Square => Some((1, 1)),
scuffle_h265::AspectRatioIdc::Aspect12_11 => Some((12, 11)),
scuffle_h265::AspectRatioIdc::Aspect10_11 => Some((10, 11)),
scuffle_h265::AspectRatioIdc::Aspect16_11 => Some((16, 11)),
scuffle_h265::AspectRatioIdc::Aspect40_33 => Some((40, 33)),
scuffle_h265::AspectRatioIdc::Aspect24_11 => Some((24, 11)),
scuffle_h265::AspectRatioIdc::Aspect20_11 => Some((20, 11)),
scuffle_h265::AspectRatioIdc::Aspect32_11 => Some((32, 11)),
scuffle_h265::AspectRatioIdc::Aspect80_33 => Some((80, 33)),
scuffle_h265::AspectRatioIdc::Aspect18_11 => Some((18, 11)),
scuffle_h265::AspectRatioIdc::Aspect15_11 => Some((15, 11)),
scuffle_h265::AspectRatioIdc::Aspect64_33 => Some((64, 33)),
scuffle_h265::AspectRatioIdc::Aspect160_99 => Some((160, 99)),
scuffle_h265::AspectRatioIdc::Aspect4_3 => Some((4, 3)),
scuffle_h265::AspectRatioIdc::Aspect3_2 => Some((3, 2)),
scuffle_h265::AspectRatioIdc::Aspect2_1 => Some((2, 1)),
scuffle_h265::AspectRatioIdc::ExtendedSar => None,
_ => None, }
}