moon-h264

    Pure-MoonBit ITU-T H.264/AVC Constrained Baseline video decoder, bit-exact FFmpeg-verified YUV420p engine, macroblock/MV inspector, and zero-upload browser player

    h264
    avc
    video
    codec
    decoder
    cavlc
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    1 hour ago
    Downloads
    3

    #moon-h264

    Pure-MoonBit ITU-T H.264 / AVC Constrained Baseline video decoder, bit-exact FFmpeg-verified YUV420p engine, white-box macroblock/MV inspector, and zero-upload browser player.

    #Highlights

    1. Bit-Exact ITU-T H.264 Constrained Baseline Decoding:
      • Full Annex B / AVCC NALU framing with Emulation Prevention Byte (0x00 0x00 0x03) stripping.
      • Complete CAVLC entropy decoder (all coeff_token, level, total_zeros, and run_before tables mathematically verified prefix-free with exact Kraft sums).
      • Exact integer inverse quantization, 4x4 IDCT, 4x4 Luma DC Hadamard, and 2x2 Chroma DC Hadamard transforms.
      • All 9 Intra_4x4, 4 Intra_16x16, 4 Chroma_8x8 modes, and I_PCM raw passthrough.
      • Full P-slice Inter decoding (P_Skip, P_16x16, P_16x8, P_8x16, P_8x8 / P_8x8ref0 with 8x8/8x4/4x8/4x4 sub-partitions), median MV prediction, 6-tap FIR 1/4-pel Luma MC, and 1/8-pel bilinear Chroma MC.
      • Full §8.7 in-loop deblocking filter (bS = 0..4, normal & strong filters, slice boundaries, alpha/beta offsets) and multi-reference DPB.
    2. 13/13 Real libx264 Streams Verified Bit-Exact Against FFmpeg:
      • Every decoded frame's cropped Y + U + V buffer matches ffmpeg -f rawvideo -pix_fmt yuv420p with 0-byte, 0-pixel error (exact SHA-256 parity, PSNR = ∞) across 94 frames at 216+ aggregate native FPS (up to 573 FPS on 160x120 and 363 FPS on 320x240).
    3. White-Box Anatomy & Zero-Upload Browser Player:
      • Exposes per-frame NALU/SPS/PPS structure, macroblock type grid, QP, bit counts, and L0 motion vectors as structured metadata and native SVGs (render_frame_mb_svg, render_bitrate_svg).
      • Interactive HTML5 Canvas player with Y/U/V plane views, MB type overlays, MV arrows, and drag-and-drop local .h264 decoding.

    #Library Quickstart

    Add "Sam-Hui-dot/moon-h264@0.1.0" to your moon.mod and import "Sam-Hui-dot/moon-h264" @h264 in moon.pkg:

    let res = @h264.decode_annexb(h264_bytes)
    for frame in res.frames {
    let yuv420p : Bytes = frame.to_yuv420p_bytes()
    let rgba8888 : Bytes = frame.to_rgba()
    let mb_svg : String = @h264.render_frame_mb_svg(frame.meta)
    ignore((yuv420p, rgba8888, mb_svg))
    }

    #CLI Usage

    # Decode Annex B .h264 to raw YUV420p moon run --target native cmd/main -- decode input.h264 --out output.yuv # Probe NALU / SPS / PPS / frame summary (text or json) moon run --target native cmd/main -- probe input.h264 --format text # Export native SVG macroblock/MV anatomy or bitrate distribution moon run --target native cmd/main -- inspect input.h264 --frame 0 --mode mb --out frame0.svg moon run --target native cmd/main -- inspect input.h264 --mode bitrate --out bitrate.svg

    #Verification & Conformance

    • See docs/conformance.md for the full feature matrix and 0.2.0 / 0.3.0 roadmap.
    • Run the 13-stream FFmpeg bit-exact differential oracle locally:

    moon build --target native --release --deny-warn cmd/main python3 demo/verify_h264.py

    #License

    Apache-2.0

    H264Error

    pub(all) suberror H264Error {
    UnexpectedEof(String)
    InvalidSyntax(String)
    UnsupportedProfile(String)
    UnsupportedFeature(String)
    MissingParameterSet(String)
    } derive(Eq,
    Debug
    )

    Errors raised while parsing or decoding an H.264/AVC bitstream.

    H264Error::equal

    fn H264Error::equal(H264Error, H264Error) -> Bool
    automatically derived

    H264Error::not_equal

    fn H264Error::not_equal(x : H264Error, y : H264Error) -> Bool
    automatically derived

    H264Error::to_repr

    automatically derived

    BitReader

    pub struct BitReader {
    data : Bytes
    bit_pos : Int
    total_bits : Int
    stop_bit_pos : Int
    }

    Big-endian bit reader over an RBSP byte buffer with Exp-Golomb decoding.

    BitReader::align_to_byte

    fn BitReader::align_to_byte(self : BitReader) -> Unit

    BitReader::is_byte_aligned

    fn BitReader::is_byte_aligned(self : BitReader) -> Bool

    BitReader::more_rbsp_data

    fn BitReader::more_rbsp_data(self : BitReader) -> Bool

    ITU-T H.264 §7.2 more_rbsp_data().

    BitReader::new

    fn BitReader::new(data : Bytes) -> BitReader

    Create a new BitReader over RBSP bytes, precomputing the RBSP stop-one bit position.

    BitReader::peek_bits

    fn BitReader::peek_bits(self : BitReader, n : Int) -> Int

    Peek n bits (0 <= n <= 31), zero-padding if fewer than n bits remain.

    BitReader::position

    fn BitReader::position(self : BitReader) -> Int

    BitReader::read_aligned_byte

    fn BitReader::read_aligned_byte(self : BitReader) -> Int raise H264Error

    Read a raw aligned byte (used by I_PCM).

    BitReader::read_bit

    fn BitReader::read_bit(self : BitReader) -> Int raise H264Error

    Read a single bit (0 or 1).

    BitReader::read_bits

    fn BitReader::read_bits(self : BitReader, n : Int) -> Int raise H264Error

    Read n bits (0 <= n <= 31) as an unsigned integer.

    BitReader::read_me

    fn BitReader::read_me(self : BitReader, is_intra : Bool) -> Int raise H264Error

    Mapped Exp-Golomb code me(v) for 4:2:0 coded_block_pattern.

    BitReader::read_se

    fn BitReader::read_se(self : BitReader) -> Int raise H264Error

    Signed Exp-Golomb code se(v) (ITU-T H.264 §9.1.1).

    BitReader::read_te

    fn BitReader::read_te(self : BitReader, max_val : Int) -> Int raise H264Error

    Truncated Exp-Golomb code te(v) (ITU-T H.264 §9.1).

    BitReader::read_ue

    fn BitReader::read_ue(self : BitReader) -> Int raise H264Error

    Unsigned Exp-Golomb code ue(v) (ITU-T H.264 §9.1).

    BitReader::remaining_bits

    fn BitReader::remaining_bits(self : BitReader) -> Int

    BitReader::skip_bits

    fn BitReader::skip_bits(self : BitReader, n : Int) -> Unit raise H264Error

    DecodeResult

    pub struct DecodeResult {
    nalus : Array[NalUnit]
    sps_list : Array[Sps]
    pps_list : Array[Pps]
    frames : Array[DecodedFrame]
    }

    Complete result of decoding an Annex B H.264 stream.

    DecodedFrame

    pub struct DecodedFrame {
    width : Int
    height : Int
    y : Bytes
    u : Bytes
    v : Bytes
    matrix_coefficients : Int
    meta : FrameMeta
    }

    A decoded YUV420p video frame (already cropped per SPS frame_cropping).

    DecodedFrame::to_rgba

    fn DecodedFrame::to_rgba(self : DecodedFrame) -> Bytes

    Convert this decoded frame to RGBA8888 using its SPS color matrix (BT.709 if matrix_coefficients == 1, else BT.601).

    DecodedFrame::to_yuv420p_bytes

    fn DecodedFrame::to_yuv420p_bytes(self : DecodedFrame) -> Bytes

    Return the raw contiguous YUV420p byte buffer (Y + U + V), bit-exact with FFmpeg -pix_fmt yuv420p.

    FrameMeta

    pub struct FrameMeta {
    frame_index : Int
    frame_num : Int
    is_idr : Bool
    slice_type : String
    width : Int
    height : Int
    mb_w : Int
    mb_h : Int
    slice_qp : Int
    nal_bytes : Int
    mbs : Array[MbMeta]
    }

    Per-frame white-box metadata.

    H264Decoder

    pub struct H264Decoder {
    sps_map : Map[Int, Sps]
    pps_map : Map[Int, Pps]
    next_pic_id : Int
    frame_count : Int
    slice_counter : Int
    // private fields
    }

    Stateful H.264 Constrained Baseline Decoder.

    H264Decoder::flush

    fn H264Decoder::flush(self : H264Decoder) -> DecodedFrame?

    Flush any remaining in-progress picture at end of stream.

    H264Decoder::new

    H264Decoder::push_nalu

    fn H264Decoder::push_nalu(self : H264Decoder, nalu : NalUnit) -> DecodedFrame? raise H264Error

    Push a single parsed NAL unit into the decoder; returns a completed DecodedFrame if this NALU closed a previous picture.

    MbKind

    pub enum MbKind {
    I4x4
    I16x16
    IPcm
    PSkip
    P16x16
    P16x8
    P8x16
    P8x8
    }

    Macroblock type classification for inspection and visualization.

    MbKind::label

    fn MbKind::label(self : MbKind) -> String

    MbMeta

    pub struct MbMeta {
    mb_x : Int
    mb_y : Int
    kind : MbKind
    qp : Int
    bits : Int
    mv_x : Int
    mv_y : Int
    intra_mode : Int
    }

    Per-macroblock metadata captured during decoding for white-box inspection.

    MmcoOp

    pub struct MmcoOp {
    op : Int
    arg1 : Int
    arg2 : Int
    }

    Memory Management Control Operation (MMCO) command.

    NalUnit

    pub struct NalUnit {
    nal_ref_idc : Int
    nal_unit_type : Int
    byte_offset : Int
    raw_size : Int
    rbsp : Bytes
    }

    Parsed H.264 Network Abstraction Layer Unit (NALU).

    Pps

    pub struct Pps {
    pps_id : Int
    sps_id : Int
    entropy_coding_mode_flag : Bool
    bottom_field_pic_order_in_frame_present_flag : Bool
    num_slice_groups_minus1 : Int
    num_ref_idx_l0_default_active_minus1 : Int
    num_ref_idx_l1_default_active_minus1 : Int
    weighted_pred_flag : Bool
    weighted_bipred_idc : Int
    pic_init_qp_minus26 : Int
    pic_init_qs_minus26 : Int
    chroma_qp_index_offset : Int
    deblocking_filter_control_present_flag : Bool
    constrained_intra_pred_flag : Bool
    redundant_pic_cnt_present_flag : Bool
    }

    Picture Parameter Set (PPS) parsed from NALU type 8.

    RefPicListMod

    pub struct RefPicListMod {
    idc : Int
    value : Int
    }

    Reference picture list modification command (L0).

    SliceHeader

    pub struct SliceHeader {
    first_mb_in_slice : Int
    slice_type : Int
    pps_id : Int
    frame_num : Int
    is_idr : Bool
    nal_ref_idc : Int
    idr_pic_id : Int
    pic_order_cnt_lsb : Int
    delta_pic_order_cnt_0 : Int
    delta_pic_order_cnt_1 : Int
    num_ref_idx_l0_active : Int
    ref_pic_list_mods_l0 : Array[RefPicListMod]
    no_output_of_prior_pics_flag : Bool
    long_term_reference_flag : Bool
    adaptive_ref_pic_marking_mode_flag : Bool
    mmco_ops : Array[MmcoOp]
    slice_qp_y : Int
    disable_deblocking_filter_idc : Int
    slice_alpha_c0_offset_div2 : Int
    slice_beta_offset_div2 : Int
    }

    Slice Header parsed from NALU type 1 (non-IDR) or type 5 (IDR).

    SliceHeader::is_i_slice

    fn SliceHeader::is_i_slice(self : SliceHeader) -> Bool

    SliceHeader::is_p_slice

    fn SliceHeader::is_p_slice(self : SliceHeader) -> Bool

    Sps

    pub struct Sps {
    sps_id : Int
    profile_idc : Int
    constraint_set_flags : Int
    level_idc : Int
    chroma_format_idc : Int
    bit_depth_luma : Int
    bit_depth_chroma : Int
    log2_max_frame_num : Int
    pic_order_cnt_type : Int
    log2_max_pic_order_cnt_lsb : Int
    delta_pic_order_always_zero_flag : Bool
    offset_for_non_ref_pic : Int
    offset_for_top_to_bottom_field : Int
    offset_for_ref_frame : Array[Int]
    max_num_ref_frames : Int
    gaps_in_frame_num_allowed : Bool
    pic_width_in_mbs : Int
    pic_height_in_mbs : Int
    frame_mbs_only_flag : Bool
    direct_8x8_inference_flag : Bool
    frame_cropping_flag : Bool
    crop_left : Int
    crop_right : Int
    crop_top : Int
    crop_bottom : Int
    matrix_coefficients : Int
    }

    Sequence Parameter Set (SPS) parsed from NALU type 7.

    Sps::height

    fn Sps::height(self : Sps) -> Int

    Cropped display height in pixels.

    Sps::width

    fn Sps::width(self : Sps) -> Int

    Cropped display width in pixels.

    chroma_qp_from_luma

    fn chroma_qp_from_luma(qp_y : Int, offset : Int) -> Int

    Map luma QP + chroma_qp_index_offset to chroma QP (0..39).

    deblock_frame

    fn deblock_frame(y_plane : FixedArray[Byte], u_plane : FixedArray[Byte], v_plane : FixedArray[Byte], mb_w : Int, mb_h : Int, mb_is_intra : FixedArray[Bool], mb_qp : FixedArray[Int], mb_slice_id : FixedArray[Int], mb_disable_deblock : FixedArray[Int], mb_alpha_off : FixedArray[Int], mb_beta_off : FixedArray[Int], chroma_qp_offset : Int, nnz_luma : FixedArray[Int], mv_x : FixedArray[Int], mv_y : FixedArray[Int], ref_pic_id : FixedArray[Int]) -> Unit

    Run the full ITU-T H.264 §8.7 in-loop deblocking filter over an entire decoded frame.

    decode_annexb

    fn decode_annexb(data : Bytes) -> DecodeResult raise H264Error

    Decode a complete Annex B H.264 byte stream into all frames and structural metadata.

    decode_cavlc_block

    fn decode_cavlc_block(br : BitReader, out : FixedArray[Int], start_idx : Int, max_num_coeff : Int, nc : Int) -> Int raise H264Error

    Decode a residual block via CAVLC (ITU-T H.264 §9.2) into out (in raster order for 4x4, or 0..3 for 2x2 Chroma DC). Returns total_coeff.
    • start_idx: 0 for full 16-coeff or DC block, 1 for AC-only (15 coeffs).
    • max_num_coeff: 16, 15, or 4 (Chroma DC).
    • nc: context count (-1 for Chroma DC 2x2, or >= 0 for 4x4 luma/chroma).

    decode_coeff_token

    fn decode_coeff_token(br : BitReader, nc : Int) -> (Int, Int) raise H264Error

    Decode coeff_token (TotalCoeff, TrailingOnes) per ITU-T H.264 §9.2.1 Table 9-5.

    dequant_4x4

    fn dequant_4x4(block : FixedArray[Int], qp : Int, skip_dc : Bool) -> Unit

    Dequantize a 4x4 residual block (raster order, 16 ints) in place. If skip_dc is true, index 0 is left untouched (already filled by DC Hadamard).

    ebsp_to_rbsp

    fn ebsp_to_rbsp(data : Bytes, start : Int, end_ : Int) -> Bytes

    Remove Emulation Prevention Bytes (0x00 0x00 0x03) from a raw NALU body (excluding header byte) to produce the Raw Byte Sequence Payload (RBSP).

    error_message

    fn error_message(err : Error) -> String

    Format an H264Error or generic Error into a human-readable string.

    extract_annexb_nalus

    fn extract_annexb_nalus(data : Bytes) -> Array[NalUnit]

    Extract all NAL units from an Annex B byte stream (0x000001 / 0x00000001 start codes).

    extract_avcc_nalus

    fn extract_avcc_nalus(data : Bytes, length_size? : Int) -> Array[NalUnit] raise H264Error

    Extract NAL units from an AVCC length-prefixed buffer (length_size is typically 4).

    idct_4x4_add

    fn idct_4x4_add(coeffs : FixedArray[Int], plane : FixedArray[Byte], stride : Int, x0 : Int, y0 : Int) -> Unit

    Inverse 4x4 integer DCT (H.264 §8.5.12.2), adding residual to a plane at (x0, y0).

    idct_4x4_dc_add

    fn idct_4x4_dc_add(dc_val : Int, plane : FixedArray[Byte], stride : Int, x0 : Int, y0 : Int) -> Unit

    Fast path: add a DC-only 4x4 residual block to a plane at (x0, y0).

    inverse_hadamard_chroma_dc

    fn inverse_hadamard_chroma_dc(c : FixedArray[Int], qp_c : Int) -> FixedArray[Int]

    Inverse 2x2 Hadamard transform + dequantization for Chroma DC (H.264 §8.5.11).

    inverse_hadamard_luma_dc

    fn inverse_hadamard_luma_dc(c : FixedArray[Int], qp : Int) -> FixedArray[Int]

    Inverse 4x4 Hadamard transform + dequantization for Intra_16x16 Luma DC (H.264 §8.5.10).

    mc_chroma_block

    fn mc_chroma_block(ref_c : FixedArray[Byte], dst_c : FixedArray[Byte], cw : Int, ch : Int, x0 : Int, y0 : Int, bw : Int, bh : Int, mvx : Int, mvy : Int) -> Unit

    ITU-T H.264 §8.4.2.2.2 Chroma 1/8-pixel bilinear motion compensation for a bw x bh block.

    mc_luma_block

    fn mc_luma_block(ref_y : FixedArray[Byte], dst_y : FixedArray[Byte], pic_w : Int, pic_h : Int, x0 : Int, y0 : Int, bw : Int, bh : Int, mvx : Int, mvy : Int) -> Unit

    ITU-T H.264 §8.4.2.2.1 Luma 1/4-pixel motion compensation for a bw x bh block.

    nal_unit_type_name

    fn nal_unit_type_name(nal_type : Int) -> String

    Return a human-readable name for an H.264 nal_unit_type.

    parse_pps

    fn parse_pps(rbsp : Bytes) -> Pps raise H264Error

    Parse a PPS from its RBSP bytes (ITU-T H.264 §7.3.2.2).

    parse_slice_header

    fn parse_slice_header(br : BitReader, nal_unit_type : Int, nal_ref_idc : Int, sps_map : Map[Int, Sps], pps_map : Map[Int, Pps]) -> (SliceHeader, Sps, Pps) raise H264Error

    Parse a Slice Header from a BitReader positioned at the start of a slice RBSP (ITU-T H.264 §7.3.3).

    parse_sps

    fn parse_sps(rbsp : Bytes) -> Sps raise H264Error

    Parse an SPS from its RBSP bytes (ITU-T H.264 §7.3.2.1.1).

    predict_intra_16x16

    fn predict_intra_16x16(plane : FixedArray[Byte], stride : Int, x0 : Int, y0 : Int, mode : Int, avail_top : Bool, avail_left : Bool) -> Unit

    Predict a 16x16 Luma macroblock using ITU-T H.264 §8.3.3 (4 Intra_16x16 modes).

    predict_intra_4x4

    fn predict_intra_4x4(plane : FixedArray[Byte], stride : Int, x0 : Int, y0 : Int, mode : Int, avail_top : Bool, avail_left : Bool, avail_top_right : Bool, avail_top_left : Bool) -> Unit

    Predict a 4x4 Luma block using ITU-T H.264 §8.3.1.2 (all 9 Intra_4x4 modes).

    predict_intra_chroma_8x8

    fn predict_intra_chroma_8x8(plane : FixedArray[Byte], stride : Int, x0 : Int, y0 : Int, mode : Int, avail_top : Bool, avail_left : Bool) -> Unit

    Predict an 8x8 Chroma plane (Cb or Cr) using ITU-T H.264 §8.3.4 (4 Chroma modes).

    predict_mv_l0

    fn predict_mv_l0(mv_x : FixedArray[Int], mv_y : FixedArray[Int], ref_idx : FixedArray[Int], mb_slice_id : FixedArray[Int], mb_w : Int, cur_slice_id : Int, bx : Int, by : Int, bw4 : Int, cur_ref : Int, part_mode : Int) -> (Int, Int)

    Compute ITU-T H.264 §8.4.1.3 median MV predictor for a partition at 4x4 grid coords (bx, by) with width bw4 (in 4x4 blocks). part_mode: 0=normal/16x16/8x8/etc, 1=16x8_top, 2=16x8_bot, 3=8x16_left, 4=8x16_right.

    render_bitrate_svg

    fn render_bitrate_svg(frames : Array[DecodedFrame]) -> String

    Render a native SVG per-frame bitrate & I/P bar chart across all decoded frames.

    render_frame_mb_svg

    fn render_frame_mb_svg(meta : FrameMeta) -> String

    Render a native SVG macroblock & motion-vector anatomy map for a decoded frame.

    render_probe_json

    fn render_probe_json(res : DecodeResult) -> String

    Render a structured JSON summary of the decoded stream (without raw pixel buffers).

    render_probe_text

    fn render_probe_text(res : DecodeResult) -> String

    Render a human-readable probe summary of an H.264 stream (NALUs, SPS, PPS, Frames).

    verify_cavlc_tables_integrity

    fn verify_cavlc_tables_integrity() -> Bool

    Self-check that all built-in CAVLC VLC tables are prefix-free and satisfy exact Kraft sums.

    yuv420p_to_rgba

    fn yuv420p_to_rgba(y_plane : Bytes, u_plane : Bytes, v_plane : Bytes, width : Int, height : Int, bt709? : Bool) -> Bytes

    Convert a cropped YUV420p frame to RGBA8888 using BT.601 or BT.709 (matrix_coefficients == 1).

    zigzag_4x4

    let zigzag_4x4 : FixedArray[Int]

    Zig-zag scan order for 4x4 blocks (scan_idx -> raster_idx).