<?php
/**
 * SeekQuarry/Yioop --
 * Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 * Copyright (C) 2009 - 2026  Chris Pollett chris@pollett.org
 *
 * LICENSE:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * END LICENSE
 *
 * @author Chris Pollett chris@pollett.org
 * @license https://www.gnu.org/licenses/ GPL3
 * @link https://www.seekquarry.com/
 * @copyright 2009 - 2026
 * @filesource
 *
 * This class reads H.264's own way of writing numbers. A value's length is
 * given by the zeros in front of it.
 */
namespace seekquarry\yioop\library\av_processing;
/**
 * H264Bits reads the settings an H.264 stream carries, on top of the plain
 * bit reading it inherits.
 */
final class H264Bits extends BitReader
{
    /**
     * unescape takes out the padding byte a writer adds so that the marker
     * which separates units cannot appear inside one. A reader calls it on a
     * unit before reading anything out of it, since the padding is not part of
     * what the unit says.
     *
     * @param string $stream_unit the unit read out of the stream
     * @return string the unit with the padding taken out
     */
    public static function unescape(string $stream_unit): string
    {
        /*
            A byte of three is inserted after any two zero bytes so that a
            start code cannot appear inside a unit. Taking those back out is
            a plain substitution, which the string library does far quicker
            than walking the bytes here.
        */
        return str_replace("\x00\x00\x03", "\x00\x00", $stream_unit);
    }
    /**
     * readWholeNumber reads a whole number written in the format's variable
     * length form, where a run of zeros says how many bits follow.
     *
     * @return int the number read
     */
    public function readWholeNumber(): int
    {
        $leading_zeros = 0;
        while ($this->position < $this->bit_count && $this->readBit() === 0) {
            $leading_zeros++;
            if ($leading_zeros > 32) {
                throw new VideoException('invalid Exp-Golomb code');
            }
        }
        if ($leading_zeros === 0) {
            return 0;
        }
        return (1 << $leading_zeros) - 1 + $this->readBits($leading_zeros);
    }
    /**
     * readSignedNumber reads a signed number written in that same variable
     * length form, with the values alternating either side of zero.
     *
     * @return int the number read, which may be either side of zero
     */
    public function readSignedNumber(): int
    {
        $k = $this->readWholeNumber();
        $value = intdiv($k + 1, 2);
        return ($k & 1) ? $value : -$value;
    }
    /**
     * alignToByte moves the reader forward to the next byte boundary.
     */
    public function alignToByte(): void
    {
        $this->position = ($this->position + 7) & ~7;
    }
    /**
     * hasMoreToRead says whether the unit has anything left in it. A unit ends
     * with a single bit of one and then zeros to fill out the last byte, so a
     * reader that has reached that bit has read everything the unit says. A
     * caller uses this to stop reading a list of settings whose length the unit
     * itself does not give. only the ending bit and its padding remain.
     *
     * @return bool True where something is left to read, false where
     */
    public function hasMoreToRead(): bool
    {
        if ($this->position >= $this->bit_count) {
            return false;
        }
        /* find last set bit in the buffer */
        $last = $this->bit_count - 1;
        while ($last >= 0) {
            $bits = (ord($this->bytes[$last >> 3]) >> (7 - ($last & 7))) & 1;
            if ($bits === 1) {
                break;
            }
            $last--;
        }
        return $this->position < $last;
    }
}
