//! The IEEE 1857.11 parse (`wai.image.ieee1857_11`, a candidate; format-probes §10). The
//! standard's text is not openly readable. Its open reference software writes a picture
//! header with no start code, which this parse reads as that software's writer lays it
//! out: three bytes of identifiers, the picture's height and width, and two bytes of
//! picture format. The bytes carry no signature, so the parse cannot tell this format from
//! another: it reads a payload declared to be one.

use super::Refusal;
use serde_json::{json, Value};

pub fn probe(b: &[u8]) -> Result<Value, Refusal> {
    let h = b.get(..13).ok_or(Refusal::Truncated)?;
    let ids = u32::from_be_bytes([0, h[0], h[1], h[2]]);
    let profile_id = ids >> 21;
    let level_id = (ids >> 15) & 0x3f;
    let model_id = (ids >> 12) & 7;
    let parameter_set_id = (ids >> 5) & 0x7f;
    let quality_id = ids & 0x1f;
    let height = u32::from_be_bytes([h[3], h[4], h[5], h[6]]);
    let width = u32::from_be_bytes([h[7], h[8], h[9], h[10]]);
    let fmt = u16::from_be_bytes([h[11], h[12]]);
    let depth_code = (fmt >> 11) & 7;
    let picture_format = (fmt >> 8) & 7;
    let slice_h = (fmt >> 4) & 15;
    let slice_w = fmt & 15;
    if profile_id > 2 || fmt >> 14 != 0 || !(1..=2).contains(&depth_code) || height == 0 || width == 0 {
        return Err(Refusal::ReservedValue);
    }
    Ok(json!({
        "profile_id": profile_id,
        "level_id": level_id,
        "model_id": model_id,
        "parameter_set_id": parameter_set_id,
        "quality_id": quality_id,
        "size": [width, height],
        "bit_depth": if depth_code == 1 { 8 } else { 10 },
        "picture_format": picture_format,
        "slice_size": [1u32 << (slice_w + 6), 1u32 << (slice_h + 6)],
    }))
}
