use std::fmt;
use prost::Message;
use serde_json::{json, Value};
use crate::ToBytes;
include!(concat!(env!("OUT_DIR"), "/widevine.rs"));
impl ToBytes for WidevinePsshData {
fn to_bytes(&self) -> Vec<u8> {
self.encode_to_vec()
}
}
impl WidevinePsshData {
pub fn to_json(&self) -> Value {
let mut out = json!({});
if let Some(a) = self.algorithm {
out["algorithm"] = if a == 0 {
Value::String(String::from("unencrypted"))
} else {
Value::String(String::from("Aesctr"))
};
}
if let Some(p) = &self.provider {
out["provider"] = Value::String(p.to_string());
}
if let Some(p) = &self.policy {
if !p.is_empty() {
out["policy"] = Value::String(p.to_string());
}
}
if let Some(cpi) = &self.crypto_period_index {
out["crypto_period_index"] = Value::String(cpi.to_string());
}
if let Some(gl) = &self.grouped_license {
out["grouped_licence"] = Value::String(hex::encode(gl));
}
if let Some(ps) = &self.protection_scheme {
let scheme = match widevine_pssh_data::ProtectionScheme::try_from(*ps) {
Ok(s) => String::from(s.as_str_name()),
Err(_) => format!("unknown ({ps})"),
};
out["protection_scheme"] = Value::String(scheme);
}
let mut keys = Vec::new();
for kid in &self.key_id {
keys.push(Value::String(hex::encode(kid)));
}
if !keys.is_empty() {
out["key_id"] = Value::Array(keys);
}
if let Some(cid) = &self.content_id {
out["content_id"] = Value::String(hex::encode(cid));
}
out
}
}
impl fmt::Debug for WidevinePsshData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut items = Vec::new();
if let Some(a) = &self.algorithm {
items.push(if *a == 0 { String::from("unencrypted") } else { String::from("Aesctr") });
}
if let Some(p) = &self.provider {
items.push(format!("provider: {p}"));
}
if let Some(p) = &self.policy {
if !p.is_empty() {
items.push(format!("policy: {p}"));
}
}
if let Some(cpi) = &self.crypto_period_index {
items.push(format!("crypto_period_index: {cpi}"));
}
if let Some(gl) = &self.grouped_license {
items.push(format!("grouped_licence: {}", hex::encode(gl)));
}
if let Some(ps) = &self.protection_scheme {
let scheme = match widevine_pssh_data::ProtectionScheme::try_from(*ps) {
Ok(s) => String::from(s.as_str_name()),
Err(_) => format!("unknown ({ps})"),
};
items.push(format!("protection_scheme: {scheme}"));
}
for kid in &self.key_id {
items.push(format!("keyid: {}", hex::encode(kid)));
}
if let Some(cid) = &self.content_id {
items.push(format!("content_id: {}", hex::encode(cid)));
}
write!(f, "WidevinePsshData<{}>", items.join(", "))
}
}