use crate::ToGraphqlOutput;
use async_graphql::{
InputType, InputValueError, InputValueResult, Object, Scalar, ScalarType, Value,
};
use mediatime as mt;
use super::{
super::{Timebase, TimebaseOperand, clock},
MediaInstantBound, MediaTimestamp, MediaTimestampOperand,
};
#[Scalar(name = "MediaTimestampOperand")]
impl ScalarType for MediaTimestampOperand {
fn parse(value: Value) -> InputValueResult<Self> {
exact(&value).map(Self).map_err(InputValueError::custom)
}
fn is_valid(value: &Value) -> bool {
exact(value).is_ok()
}
fn to_value(&self) -> Value {
Value::String(format!("{:#}", self.0.get()))
}
}
#[Scalar(name = "MediaInstantBound")]
impl ScalarType for MediaInstantBound {
fn parse(value: Value) -> InputValueResult<Self> {
bound(&value).map(Self).map_err(InputValueError::custom)
}
fn is_valid(value: &Value) -> bool {
bound(value).is_ok()
}
fn to_value(&self) -> Value {
Value::String(format!("{:#}", self.0.get()))
}
}
fn exact(value: &Value) -> Result<MediaTimestamp, String> {
match value {
Value::Object(object) => {
const PTS: &str = "pts";
const TIMEBASE: &str = "timebase";
if let Some(unknown) = object
.keys()
.find(|key| !matches!(key.as_str(), PTS | TIMEBASE))
{
return Err(format!(
"an exact timestamp holds `{PTS}` and `{TIMEBASE}`, not `{unknown}`"
));
}
let pts = match object.get(PTS) {
Some(Value::Number(number)) => number
.as_i64()
.ok_or_else(|| String::from("`pts` is a 64-bit integer"))?,
Some(_) => return Err(String::from("`pts` is a number")),
None => {
return Err(String::from(
"an exact timestamp states both halves; `pts` is missing",
));
}
};
let timebase = object.get(TIMEBASE).ok_or_else(|| {
String::from("an exact timestamp states both halves; `timebase` is missing")
})?;
let timebase =
<TimebaseOperand as InputType>::parse(Some(timebase.clone())).map_err(|refused| {
refused
.into_server_error(async_graphql::Pos::default())
.message
})?;
Ok(MediaTimestamp::new(mt::Timestamp::new(
pts,
Timebase::from(timebase).get(),
)))
}
Value::String(text) if text.contains('@') => text
.parse::<mt::Timestamp>()
.map(MediaTimestamp::new)
.map_err(|_| {
String::from("an exact timestamp is spelled `pts @ num/den`, as in `12345 @ MPEG_90K`")
}),
Value::String(text) => Err(format!(
"`{text}` names no exact timestamp: an identity is `pts @ num/den` or \
{{pts, timebase}}, and a clock names a position rather than a value"
)),
Value::Number(_) => Err(String::from(
"a timestamp is a count in a unit: send {pts, timebase} or \"pts @ num/den\" — \
a bare number could be a pts, a second or a nanosecond",
)),
_ => Err(String::from("a timestamp is an object or a string")),
}
}
fn bound(value: &Value) -> Result<MediaTimestamp, String> {
match value {
Value::Object(object) if object.contains_key("seconds") => {
if object.len() > 1 {
return Err(String::from("`seconds` names a position on its own"));
}
match object.get("seconds") {
Some(Value::Number(number)) => seconds(number),
_ => Err(String::from("`seconds` is a number")),
}
}
Value::Object(object) if object.contains_key("nanos") => {
if object.len() > 1 {
return Err(String::from("`nanos` names a position on its own"));
}
match object.get("nanos") {
Some(Value::Number(number)) => number
.as_i64()
.map(|nanos| MediaTimestamp::new(mt::Timestamp::new(nanos, mt::Timebase::NANOS)))
.ok_or_else(|| String::from("`nanos` is a 64-bit integer")),
_ => Err(String::from("`nanos` is a number")),
}
}
Value::String(text) if !text.contains('@') => clock::nanos(text)
.map(|nanos| MediaTimestamp::new(mt::Timestamp::new(nanos, mt::Timebase::NANOS)))
.map_err(|refused| refused.to_string()),
other => exact(other),
}
}
fn seconds(number: &async_graphql::Number) -> Result<MediaTimestamp, String> {
let seconds = number
.as_f64()
.ok_or_else(|| String::from("`seconds` is a number"))?;
if !seconds.is_finite() {
return Err(String::from("`seconds` is a finite number"));
}
let nanos = (seconds * 1e9).round();
if nanos < i64::MIN as f64 || nanos > i64::MAX as f64 {
return Err(String::from(
"the position is further from zero than 292 years of nanoseconds",
));
}
Ok(MediaTimestamp::new(mt::Timestamp::new(
nanos as i64,
mt::Timebase::NANOS,
)))
}
impl ToGraphqlOutput for MediaTimestamp {
type Output<'a> = &'a Self;
#[inline]
fn to_graphql_output(timestamp: &Self) -> Self::Output<'_> {
timestamp
}
}
#[Object]
impl MediaTimestamp {
#[doc(hidden)]
#[graphql(name = "pts")]
async fn __async_graphql_pts__(&self) -> i64 {
self.get().pts()
}
#[doc(hidden)]
#[graphql(name = "timebase")]
async fn __async_graphql_timebase__(&self) -> Timebase {
Timebase::new(self.get().timebase())
}
#[doc(hidden)]
#[graphql(name = "nanos")]
async fn __async_graphql_nanos__(&self) -> Option<i64> {
self.to_nanos().ok()
}
#[doc(hidden)]
#[graphql(name = "seconds")]
async fn __async_graphql_seconds__(&self) -> Option<f64> {
self.to_nanos().ok().map(|nanos| nanos as f64 / 1e9)
}
#[doc(hidden)]
#[graphql(name = "clock")]
async fn __async_graphql_clock__(&self) -> Option<String> {
self
.to_nanos()
.ok()
.map(|nanos| clock::render(nanos).as_str().to_owned())
}
}