use crate::ToGraphqlOutput;
use async_graphql::{
InputType, InputValueError, InputValueResult, Object, Scalar, ScalarType, Value,
};
use mediatime as mt;
use super::{
super::{MediaInstantBound, MediaTimestamp, Timebase, clock},
MediaContained, MediaContainedOperand, MediaDurationBound, MediaSpanBound, MediaTimeRange,
MediaTimeRangeOperand,
};
#[Scalar(name = "MediaTimeRangeOperand")]
impl ScalarType for MediaTimeRangeOperand {
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()))
}
}
fn exact(value: &Value) -> Result<MediaTimeRange, String> {
match value {
Value::String(text) => text
.parse::<mt::TimeRange>()
.map(MediaTimeRange::new)
.map_err(|_| {
String::from(
"an exact range is spelled `[start, end) @ num/den`, as in `[100, 250) @ MPEG_90K`",
)
}),
Value::Object(object) => {
const START: &str = "start";
const END: &str = "end";
const TIMEBASE: &str = "timebase";
if let Some(unknown) = object
.keys()
.find(|key| !matches!(key.as_str(), START | END | TIMEBASE))
{
return Err(format!(
"an exact range holds `{START}`, `{END}` and `{TIMEBASE}`, not `{unknown}`"
));
}
let count = |key: &str| -> Result<i64, String> {
match object.get(key) {
Some(Value::Number(number)) => number
.as_i64()
.ok_or_else(|| format!("`{key}` is a 64-bit integer")),
Some(_) => Err(format!("`{key}` is a count in the timebase beside it")),
None => Err(format!(
"an exact range states both counts and a timebase; `{key}` is missing"
)),
}
};
let start = count(START)?;
let end = count(END)?;
let timebase = object.get(TIMEBASE).ok_or_else(|| {
String::from("an exact range states both counts and a timebase; `timebase` is missing")
})?;
let timebase = <super::super::TimebaseOperand as InputType>::parse(Some(timebase.clone()))
.map_err(|refused| {
refused
.into_server_error(async_graphql::Pos::default())
.message
})?;
mt::TimeRange::try_new(start, end, Timebase::from(timebase).get())
.map(MediaTimeRange::new)
.ok_or_else(|| String::from("a range's end must not precede its start"))
}
Value::Number(_) => Err(String::from(
"a range is two counts and a timebase: send {start, end, timebase} or \
\"[start, end) @ num/den\"",
)),
_ => Err(String::from("a range is an object or a string")),
}
}
#[Scalar(name = "MediaSpanBound")]
impl ScalarType for MediaSpanBound {
fn parse(value: Value) -> InputValueResult<Self> {
span(&value).map(Self).map_err(InputValueError::custom)
}
fn is_valid(value: &Value) -> bool {
span(value).is_ok()
}
fn to_value(&self) -> Value {
Value::String(format!("{:#}", self.0.get()))
}
}
#[Scalar(name = "MediaContainedOperand")]
impl ScalarType for MediaContainedOperand {
fn parse(value: Value) -> InputValueResult<Self> {
contained(&value).map(Self).map_err(InputValueError::custom)
}
fn is_valid(value: &Value) -> bool {
contained(value).is_ok()
}
fn to_value(&self) -> Value {
match self.0 {
MediaContained::Instant(instant) => Value::String(format!("{:#}", instant.get())),
MediaContained::Span(span) => Value::String(format!("{:#}", span.get())),
}
}
}
#[Scalar(name = "MediaDurationBound")]
impl ScalarType for MediaDurationBound {
fn parse(value: Value) -> InputValueResult<Self> {
duration(&value).map(Self).map_err(InputValueError::custom)
}
fn is_valid(value: &Value) -> bool {
duration(value).is_ok()
}
fn to_value(&self) -> Value {
Value::String(format!("{:#}", self.0))
}
}
fn span(value: &Value) -> Result<MediaTimeRange, String> {
match value {
Value::String(text) if text.trim_start().starts_with('[') => text
.parse::<mt::TimeRange>()
.map(MediaTimeRange::new)
.map_err(|_| {
String::from("a span is spelled `[start, end) @ num/den`, as in `[100, 250) @ MPEG_90K`")
}),
Value::Object(object) => {
const START: &str = "start";
const END: &str = "end";
if let Some(unknown) = object
.keys()
.find(|key| !matches!(key.as_str(), START | END))
{
return Err(format!(
"a span holds `{START}` and `{END}`, not `{unknown}`"
));
}
let half = |key: &str| -> Result<MediaTimestamp, String> {
let sent = object
.get(key)
.ok_or_else(|| format!("a span states both endpoints; `{key}` is missing"))?;
<MediaInstantBound as InputType>::parse(Some(sent.clone()))
.map(MediaTimestamp::from)
.map_err(|refused| {
refused
.into_server_error(async_graphql::Pos::default())
.message
})
};
let start = half(START)?
.to_nanos()
.map_err(|overflow| overflow.to_string())?;
let end = half(END)?
.to_nanos()
.map_err(|overflow| overflow.to_string())?;
mt::TimeRange::try_new(start, end, mt::Timebase::NANOS)
.map(MediaTimeRange::new)
.ok_or_else(|| String::from("a span's end must not precede its start"))
}
Value::Number(_) => Err(String::from(
"a span is two positions: send {start, end} or \"[start, end) @ num/den\"",
)),
_ => Err(String::from("a span is an object or a string")),
}
}
fn contained(value: &Value) -> Result<MediaContained, String> {
let is_span = match value {
Value::String(text) => text.trim_start().starts_with('['),
Value::Object(object) => object.contains_key("start") || object.contains_key("end"),
_ => false,
};
if is_span {
span(value).map(MediaContained::Span)
} else {
<MediaInstantBound as InputType>::parse(Some(value.clone()))
.map(|bound| MediaContained::Instant(bound.into()))
.map_err(|refused| {
refused
.into_server_error(async_graphql::Pos::default())
.message
})
}
}
fn duration(value: &Value) -> Result<mt::SignedDuration, String> {
let of_nanos = |nanos: i64| mt::SignedDuration::new(nanos, mt::Timebase::NANOS);
match value {
Value::String(text) if text.contains('@') => text.parse::<mt::SignedDuration>().map_err(|_| {
String::from("an exact length is spelled `ticks @ num/den`, as in `-1500 @ MILLIS`")
}),
Value::String(text) => clock::nanos(text)
.map(of_nanos)
.map_err(|refused| refused.to_string()),
Value::Object(_) => {
<MediaInstantBound as InputType>::parse(Some(value.clone()))
.map_err(|refused| {
refused
.into_server_error(async_graphql::Pos::default())
.message
})
.and_then(|bound| {
MediaTimestamp::from(bound)
.to_nanos()
.map(of_nanos)
.map_err(|overflow| overflow.to_string())
})
}
Value::Number(_) => Err(String::from(
"a length is a count in a unit: send {seconds}, {nanos}, a clock, or \"ticks @ num/den\"",
)),
_ => Err(String::from("a length is an object or a string")),
}
}
impl ToGraphqlOutput for MediaTimeRange {
type Output<'a> = &'a Self;
#[inline]
fn to_graphql_output(range: &Self) -> Self::Output<'_> {
range
}
}
#[Object]
impl MediaTimeRange {
#[doc(hidden)]
#[graphql(name = "start")]
async fn __async_graphql_start__(&self) -> i64 {
self.get().start_pts()
}
#[doc(hidden)]
#[graphql(name = "end")]
async fn __async_graphql_end__(&self) -> i64 {
self.get().end_pts()
}
#[doc(hidden)]
#[graphql(name = "timebase")]
async fn __async_graphql_timebase__(&self) -> Timebase {
Timebase::new(self.get().timebase())
}
#[doc(hidden)]
#[graphql(name = "startInstant")]
async fn __async_graphql_start_instant__(&self) -> MediaTimestamp {
self.start()
}
#[doc(hidden)]
#[graphql(name = "endInstant")]
async fn __async_graphql_end_instant__(&self) -> MediaTimestamp {
self.end()
}
#[doc(hidden)]
#[graphql(name = "durationNanos")]
async fn __async_graphql_duration_nanos__(&self) -> Option<i64> {
self.duration_nanos().ok()
}
#[doc(hidden)]
#[graphql(name = "durationSeconds")]
async fn __async_graphql_duration_seconds__(&self) -> Option<f64> {
self.duration_nanos().ok().map(|nanos| nanos as f64 / 1e9)
}
#[doc(hidden)]
#[graphql(name = "durationClock")]
async fn __async_graphql_duration_clock__(&self) -> Option<String> {
self
.duration_nanos()
.ok()
.map(|nanos| clock::render(nanos).as_str().to_owned())
}
}