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;
pub struct Import<E: CatalogExt = ()> {
track: crate::container::Producer<crate::catalog::hang::Container>,
rendition: crate::catalog::VideoTrack<E>,
catalog: crate::codec::video::Catalog,
last_sps: Option<Bytes>,
}
impl<E: CatalogExt> Import<E> {
pub fn new(
track: moq_net::track::Producer,
reserved: crate::catalog::Reserved<E>,
hint: crate::catalog::VideoHint,
) -> crate::Result<Self> {
let rendition = reserved.video(track.name());
let catalog = crate::codec::video::Catalog::new(&reserved, track.name(), hint)?;
let mut import = Self {
track: reserved
.producer()
.media_producer(track, crate::catalog::hang::Container::Legacy)?,
rendition,
catalog,
last_sps: None,
};
if let Some(config) = import.catalog.initial_config() {
import.apply_config(config);
}
Ok(import)
}
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::track::Demand {
self.track.track().demand()
}
pub fn finish(&mut self) -> Result<()> {
self.rendition.record_group_end(None);
self.track.finish()?;
Ok(())
}
pub fn abort(self, err: moq_net::Error) {
self.track.abort(err);
}
pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> Result<()> {
self.rendition.record_group_end(end);
self.track.cut(end)?;
Ok(())
}
pub fn seek(&mut self, sequence: u64) -> Result<()> {
self.rendition.record_group_end(None);
self.track.seek(sequence)?;
Ok(())
}
pub fn observe_reorder(&mut self, reorder: moq_net::Timestamp) {
self.rendition.record_reorder(reorder);
}
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_aspect_width = vui_data.display_ratio_width;
config.display_aspect_height = vui_data.display_ratio_height;
config.container = hang::catalog::Container::Legacy;
self.last_sps = Some(sps_nal.clone());
self.apply_config(config);
Ok(())
}
fn apply_config(&mut self, config: hang::catalog::VideoConfig) {
self.catalog.publish(&mut self.rendition, config);
}
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.catalog.configured() {
return Err(Error::MissingSps.into());
}
if frame.keyframe {
self.rendition.record_group_end(Some(frame.timestamp));
}
let pts = frame.timestamp;
let bytes = frame.payload.len();
self.track.write(frame)?;
self.rendition.record_frame(pts, bytes);
}
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, }
}