<?php
/**
 * Streaming local writer for prepared hash-mode media signing.
 *
 * @package EncypherProvenance
 */

namespace EncypherProvenance;

if (! defined('ABSPATH')) {
    exit;
}

class HashMediaWriter
{
    private const COPY_CHUNK = 1_048_576;
    private const C2PA_UUID_HEX = 'd8fec3d61b0e483c92975828877ec481';
    private const BMFF_EXCLUSIONS = ['/uuid', '/ftyp', '/mfra', '/free', '/skip'];
    private const BMFF_EXCLUDED_TYPES = ['ftyp', 'mfra', 'free', 'skip'];
    private const MAX_BMFF_PATCH_ITEMS = 65_536;
    private const MAX_BMFF_PATCH_RUNS = 8_192;
    private const MAX_PLAN_ITEMS = 16_384;
    private const MAX_DECODED_PLAN_BYTES = 50_331_648;
    private const MAX_MANIFEST_BYTES = 262_144;
    private const MAX_CARRIER_BYTES = 524_288;

    /**
     * Hash-mode replacement requires a local path with atomic rename semantics.
     */
    public static function is_local_path(string $file_path): bool
    {
        if (function_exists('wp_is_stream') && wp_is_stream($file_path)) {
            return false;
        }

        return 1 !== preg_match('#^[a-z][a-z0-9+.-]*://#i', $file_path);
    }

    /**
     * Hold the original inode locked while all signing work reads a private,
     * immutable snapshot.
     *
     * @param callable $operation fn(resource,array<string,mixed>): array|WP_Error
     * @return array|\WP_Error
     */
    public static function with_locked_source(string $file_path, callable $operation, ?callable $heartbeat = null)
    {
        if (! self::is_local_path($file_path)) {
            return new \WP_Error('media_non_local_path', 'Hash signing requires a local media file.');
        }

        $original = @fopen($file_path, 'rb'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- A held native inode is required to detect content and pathname replacement.
        if (false === $original) {
            return new \WP_Error('media_read_failed', 'Could not open the local media file for hash signing.');
        }
        if (! flock($original, LOCK_EX)) { // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_flock -- The source inode remains locked through atomic replacement.
            fclose($original);
            return new \WP_Error('media_lock_failed', 'Could not lock the local media file for hash signing.');
        }

        $snapshot = null;
        $snapshot_path = '';
        try {
            $original_stat = fstat($original);
            clearstatcache(true, $file_path);
            $path_stat = @stat($file_path); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_stat -- Establish that the opened inode is still the pathname authority.
            if (
                ! is_array($original_stat)
                || ! is_array($path_stat)
                || ! self::same_identity($original_stat, $path_stat)
            ) {
                return new \WP_Error('source_changed', 'The media file path changed before hash signing started.');
            }

            $snapshot_path = tempnam(dirname($file_path), '.encypher-source-'); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_tempnam -- The private snapshot must be local and independently seekable.
            if (false === $snapshot_path) {
                $snapshot_path = '';
                return new \WP_Error('media_temp_failed', 'Could not create a private source snapshot.');
            }
            // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.chmod_chmod -- Source snapshots must never inherit public upload permissions.
            if (! @chmod($snapshot_path, 0600)) {
                return new \WP_Error('media_temp_failed', 'Could not make the source snapshot private.');
            }
            $snapshot = @fopen($snapshot_path, 'w+b'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Snapshot copying and sparse planning require a seekable native stream.
            if (false === $snapshot) {
                $snapshot = null;
                return new \WP_Error('media_temp_failed', 'Could not open the private source snapshot.');
            }

            if (0 !== fseek($original, 0, SEEK_SET)) {
                return new \WP_Error('media_read_failed', 'Could not read the local media file for hash signing.');
            }
            $snapshot_hash = hash_init('sha256');
            $lease = self::check_heartbeat($heartbeat);
            if (is_wp_error($lease)) {
                return $lease;
            }
            while (! feof($original)) {
                $lease = self::check_heartbeat($heartbeat);
                if (is_wp_error($lease)) {
                    return $lease;
                }
                $chunk = fread($original, self::COPY_CHUNK); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- The pinned source snapshot requires a bounded read from the already locked native stream.
                if (false === $chunk || ('' === $chunk && ! feof($original))) {
                    return new \WP_Error('media_read_failed', 'Could not copy the local media file for hash signing.');
                }
                if ('' === $chunk) {
                    break;
                }
                hash_update($snapshot_hash, $chunk);
                $written = self::write_all($snapshot, $chunk, $heartbeat);
                if (is_wp_error($written)) {
                    return $written;
                }
            }
            fflush($snapshot);
            if (function_exists('fsync')) {
                fsync($snapshot);
            }
            $pinned_hash = hash_final($snapshot_hash);
            $original_hash = self::hash_stream($original, $heartbeat);
            if (is_wp_error($original_hash)) {
                return $original_hash;
            }
            if (! hash_equals($pinned_hash, $original_hash)) {
                return new \WP_Error('source_changed', 'The media file changed while its private snapshot was created.');
            }
            $snapshot_stat = fstat($snapshot);
            clearstatcache(true, $file_path);
            $path_stat = @stat($file_path); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_stat -- Reject pathname replacement before any local planning.
            if (
                ! is_array($snapshot_stat)
                || (int) ($snapshot_stat['size'] ?? -1) !== (int) ($original_stat['size'] ?? -2)
                || ! is_array($path_stat)
                || ! self::same_identity($original_stat, $path_stat)
            ) {
                return new \WP_Error('source_changed', 'The media file changed before hash signing started.');
            }
            $snapshot_stat['_original_handle'] = $original;
            $snapshot_stat['_original_stat'] = $original_stat;
            $snapshot_stat['_snapshot_sha256'] = $pinned_hash;
            return $operation($snapshot, $snapshot_stat);
        } finally {
            if (is_resource($snapshot)) {
                fclose($snapshot);
            }
            if ('' !== $snapshot_path && file_exists($snapshot_path)) {
                @unlink($snapshot_path); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_unlink -- Always remove the private source snapshot.
            }
            flock($original, LOCK_UN); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_flock -- Release the original inode after commit or failure.
            fclose($original);
        }
    }

    /**
     * Authorize a prepared edit against locally parsed geometry, hash the
     * local digest program, obtain and verify the carrier, then atomically
     * replace the source.
     *
     * @param resource $source
     * @param array<string,mixed> $source_stat
     * @param array<string,mixed> $plan
     * @param callable $finalize fn(string): array|WP_Error
     * @param callable|null $heartbeat fn(): bool
     * @return array|\WP_Error Finalize response plus signed_file_sha256.
     */
    public static function apply_and_commit(
        $source,
        array $source_stat,
        string $file_path,
        array $plan,
        callable $finalize,
        ?callable $heartbeat = null
    ) {
        if (! self::is_local_path($file_path)) {
            return new \WP_Error('media_non_local_path', 'Hash signing requires a local media file.');
        }

        $original = $source_stat['_original_handle'] ?? null;
        $original_stat = $source_stat['_original_stat'] ?? null;
        $snapshot_sha256 = $source_stat['_snapshot_sha256'] ?? null;
        if (
            ! is_resource($source)
            || ! is_resource($original)
            || ! is_array($original_stat)
            || ! is_string($snapshot_sha256)
            || 1 !== preg_match('/\A[0-9a-f]{64}\z/', $snapshot_sha256)
        ) {
            return new \WP_Error('source_authority_invalid', 'Hash signing requires a pinned private source snapshot.');
        }

        $bounds = self::validate_plan_bounds($source_stat, $plan);
        if (is_wp_error($bounds)) {
            return $bounds;
        }

        $temp_path = tempnam(dirname($file_path), '.encypher-hash-'); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_tempnam -- Atomic replacement requires a private temporary file in the attachment's upload directory.
        if (false === $temp_path) {
            return new \WP_Error('media_temp_failed', 'Could not create a local signing file.');
        }
        $temp = @fopen($temp_path, 'w+b'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Local splice output requires a seekable stream; WP_Filesystem cannot seek or preserve same-directory atomic replacement.
        if (false === $temp) {
            @unlink($temp_path); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_unlink -- Remove the private upload-directory temporary file when opening it fails.
            return new \WP_Error('media_temp_failed', 'Could not open the local signing file.');
        }

        try {
            $program = self::derive_hash_program($source, $source_stat, $plan);
            if (is_wp_error($program)) {
                return $program;
            }
            $geometry = self::apply_edits($source, $temp, $plan, $heartbeat);
            if (is_wp_error($geometry)) {
                return $geometry;
            }
            $digest = self::hash_program($source, $program, $heartbeat);
            if (is_wp_error($digest)) {
                return $digest;
            }
            $result = $finalize($digest);
            if (is_wp_error($result)) {
                return $result;
            }

            $material = self::decode_finalize_material($result, $plan);
            if (is_wp_error($material)) {
                return $material;
            }
            [$carrier, $manifest] = $material;
            $carrier_start = (int) ($geometry['carrier_start'] ?? -1);
            $carrier_length = (int) ($geometry['carrier_length'] ?? -1);
            $carrier_span = $plan['carrier_span'] ?? null;
            $output_span = $plan['carrier_output_span'] ?? null;
            if (
                $carrier_start < 0
                || strlen($carrier) !== $carrier_length
                || $carrier_span !== ['offset' => 0, 'length' => $carrier_length]
                || $output_span !== ['offset' => $carrier_start, 'length' => $carrier_length]
            ) {
                return new \WP_Error('carrier_geometry_mismatch', 'The signed carrier does not match the prepared file geometry.');
            }
            $verified = self::validate_finalize_result($result, $plan, $digest, $carrier, $manifest, $source);
            if (is_wp_error($verified)) {
                return $verified;
            }
            if (0 !== fseek($temp, $carrier_start, SEEK_SET)) {
                return new \WP_Error('media_write_failed', 'Could not place the signed manifest carrier.');
            }
            $carrier_write = self::write_all($temp, $carrier, $heartbeat);
            if (is_wp_error($carrier_write)) {
                return $carrier_write;
            }
            fflush($temp);
            if (function_exists('fsync')) {
                fsync($temp);
            }
            $temp_stat = fstat($temp);
            if (! is_array($temp_stat) || (int) ($temp_stat['size'] ?? -1) !== (int) ($plan['expected_final_size'] ?? -2)) {
                return new \WP_Error('final_size_mismatch', 'The locally assembled signed file has the wrong size.');
            }

            $assembled_digest = self::hash_assembled_output($temp, $plan, $carrier_start, $carrier_length, $heartbeat);
            if (is_wp_error($assembled_digest)) {
                return $assembled_digest;
            }
            if (! hash_equals($digest, $assembled_digest)) {
                return new \WP_Error('hard_binding_mismatch', 'The assembled signed file does not match the locally derived hard binding.');
            }
            $signed_sha256 = self::hash_stream($temp, $heartbeat);
            if (is_wp_error($signed_sha256)) {
                return $signed_sha256;
            }
            // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.chmod_chmod -- Required to preserve original source permissions during atomic replacement.
            @chmod($temp_path, ((int) ($original_stat['mode'] ?? 0644)) & 0777);
            fclose($temp);
            $temp = null;
            $lease = self::check_heartbeat($heartbeat);
            if (is_wp_error($lease)) {
                return $lease;
            }
            $current_source_hash = self::hash_stream($original, $heartbeat);
            if (is_wp_error($current_source_hash) || ! hash_equals($snapshot_sha256, $current_source_hash)) {
                return new \WP_Error('source_changed', 'The media file changed while it was being signed.');
            }
            $after = fstat($original);
            clearstatcache(true, $file_path);
            $path_stat = @stat($file_path); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_stat -- The pathname must still resolve to the held original inode immediately before atomic replacement.
            if (
                ! is_array($after)
                || ! self::same_identity($original_stat, $after)
                || ! is_array($path_stat)
                || ! self::same_identity($original_stat, $path_stat)
            ) {
                return new \WP_Error('source_changed', 'The media file path changed while it was being signed.');
            }
            if (! @rename($temp_path, $file_path)) { // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_rename -- Same-directory rename atomically replaces the locked local attachment without a partial-file window.
                return new \WP_Error('media_replace_failed', 'Could not atomically replace the local media file.');
            }
            $temp_path = '';
            $result['signed_file_sha256'] = $signed_sha256;
            $result['binding_digest'] = $digest;
            return $result;
        } finally {
            if (is_resource($temp)) {
                fclose($temp);
            }
            if ('' !== $temp_path && file_exists($temp_path)) {
                @unlink($temp_path); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_unlink -- Failure cleanup removes only the private temporary file created above.
            }
        }
    }

    /**
     * Reject plans that can exhaust local storage or memory before creating an
     * output file. The typed edit list is the sole wire authority for output size.
     *
     * @return true|\WP_Error
     */
    private static function validate_plan_bounds(array $source_stat, array $plan)
    {
        $source_size = self::strict_nonnegative_int($source_stat['size'] ?? null);
        $expected_size = self::strict_nonnegative_int($plan['expected_final_size'] ?? null);
        $edits = $plan['edits'] ?? null;
        if (null === $source_size || null === $expected_size || ! is_array($edits) || [] === $edits) {
            return new \WP_Error('plan_invalid', 'The signing plan geometry is missing.');
        }
        if (count($edits) > self::MAX_PLAN_ITEMS) {
            return new \WP_Error('plan_too_large', 'The signing plan contains too many edit operations.');
        }

        $inserted = 0;
        $deleted = 0;
        $decoded_bytes = 0;
        foreach ($edits as $edit) {
            if (
                ! is_array($edit)
                || 3 !== count($edit)
                || ! is_string($edit['op'] ?? null)
                || null === self::strict_nonnegative_int($edit['offset'] ?? null)
            ) {
                return new \WP_Error('plan_invalid', 'The signing edit list is malformed.');
            }
            if ('insert_carrier' === $edit['op']) {
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                if (null === $length || $length <= 0) {
                    return new \WP_Error('plan_invalid', 'The signing carrier length is invalid.');
                }
                if ($length > self::MAX_DECODED_PLAN_BYTES - $decoded_bytes) {
                    return new \WP_Error('plan_too_large', 'The signing plan exceeds the local material limit.');
                }
                $decoded_bytes += $length;
                $inserted += $length;
            } elseif ('delete' === $edit['op']) {
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                if (null === $length || $length <= 0 || $length > $source_size - $deleted) {
                    return new \WP_Error('plan_invalid', 'The signing delete length is invalid.');
                }
                $deleted += $length;
            } elseif ('patch' === $edit['op']) {
                $consumed = self::consume_plan_literal($decoded_bytes, $edit['b64'] ?? null);
                if (is_wp_error($consumed)) {
                    return $consumed;
                }
            } else {
                return new \WP_Error('plan_invalid', 'The signing edit list contains an unknown operation.');
            }
        }

        if ($source_size - $deleted + $inserted !== $expected_size) {
            return new \WP_Error('plan_geometry_mismatch', 'The signing edits do not match the expected file size.');
        }
        return true;
    }

    /** @return true|\WP_Error */
    private static function consume_plan_literal(int &$decoded_bytes, $encoded)
    {
        $remaining = self::MAX_DECODED_PLAN_BYTES - $decoded_bytes;
        if (
            ! is_string($encoded)
            || '' === $encoded
            || strlen($encoded) > 4 * intdiv($remaining + 2, 3)
        ) {
            return new \WP_Error('plan_too_large', 'The signing plan contains an invalid or oversized literal.');
        }
        $literal = base64_decode($encoded, true);
        if (false === $literal || '' === $literal || base64_encode($literal) !== $encoded) {
            return new \WP_Error('plan_invalid', 'The signing plan contains an invalid literal.');
        }
        $length = strlen($literal);
        if ($length > $remaining) {
            return new \WP_Error('plan_too_large', 'The signing plan exceeds the local material limit.');
        }
        $decoded_bytes += $length;
        return true;
    }

    /** @return array{carrier_start:int,carrier_length:int}|\WP_Error */
    private static function apply_edits($source, $output, array $plan, ?callable $heartbeat)
    {
        $edits = $plan['edits'] ?? null;
        $source_size = (int) (fstat($source)['size'] ?? -1);
        if (! is_array($edits) || $source_size < 0) {
            return new \WP_Error('plan_invalid', 'The signing edit list is missing.');
        }
        $cursor = 0;
        $carrier_start = -1;
        $carrier_length = -1;
        foreach ($edits as $edit) {
            if (! is_array($edit) || ! is_string($edit['op'] ?? null)) {
                return new \WP_Error('plan_invalid', 'The signing edit list is malformed.');
            }
            $offset = self::strict_nonnegative_int($edit['offset'] ?? null);
            if ('insert_carrier' === $edit['op']) {
                if ($carrier_start >= 0) {
                    return new \WP_Error('plan_invalid', 'The signing edit list contains more than one manifest carrier.');
                }
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                $kind = 'insert';
            } elseif ('delete' === $edit['op']) {
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                $kind = 'delete';
            } elseif ('patch' === $edit['op']) {
                $bytes = base64_decode((string) ($edit['b64'] ?? ''), true);
                if (false === $bytes || '' === $bytes || base64_encode($bytes) !== ($edit['b64'] ?? null)) {
                    return new \WP_Error('plan_invalid', 'A signing patch is not valid canonical base64.');
                }
                $length = strlen($bytes);
                $kind = 'patch';
            } else {
                return new \WP_Error('plan_invalid', 'The signing edit list contains an unknown operation.');
            }
            if (null === $offset || null === $length || $length <= 0 || $offset < $cursor || $offset > $source_size) {
                return new \WP_Error('plan_invalid', 'A signing edit operation is out of order or out of bounds.');
            }
            $copied = self::copy_range($source, $output, $cursor, $offset - $cursor, $heartbeat);
            if (is_wp_error($copied)) {
                return $copied;
            }
            $cursor = $offset;
            if ('insert' === $kind) {
                $carrier_start = (int) ftell($output);
                $carrier_length = $length;
                $reserved = self::write_zeros($output, $length, $heartbeat);
                if (is_wp_error($reserved)) {
                    return $reserved;
                }
            } elseif ('delete' === $kind) {
                if ($cursor + $length > $source_size) {
                    return new \WP_Error('plan_invalid', 'A signing delete is out of bounds.');
                }
                $cursor += $length;
            } else {
                if ($cursor + $length > $source_size) {
                    return new \WP_Error('media_write_failed', 'Could not apply a signing patch.');
                }
                $patched = self::write_all($output, $bytes, $heartbeat);
                if (is_wp_error($patched)) {
                    return $patched;
                }
                $cursor += $length;
            }
        }
        $copied = self::copy_range($source, $output, $cursor, $source_size - $cursor, $heartbeat);
        if (is_wp_error($copied)) {
            return $copied;
        }
        fflush($output);
        $stat = fstat($output);
        if (! is_array($stat) || (int) $stat['size'] !== (int) ($plan['expected_final_size'] ?? -1)) {
            return new \WP_Error('plan_geometry_mismatch', 'The signing edits produced the wrong file size.');
        }
        return ['carrier_start' => $carrier_start, 'carrier_length' => $carrier_length];
    }

    /**
     * Derive the only hash program allowed by the locally validated edit
     * geometry.
     *
     * @return array<int,array<string,mixed>>|\WP_Error
     */
    private static function derive_hash_program($source, array $source_stat, array $plan)
    {
        $source_size = (int) ($source_stat['size'] ?? -1);
        $expected_size = $plan['expected_final_size'] ?? null;
        $edits = $plan['edits'] ?? null;
        if ($source_size < 0 || ! is_int($expected_size) || ! is_array($edits) || [] === $edits) {
            return new \WP_Error('plan_invalid', 'The signing plan geometry is missing.');
        }
        $binding = $plan['binding_algorithm'] ?? 'c2pa.hash.data';
        if ('c2pa.hash.bmff.v3' === $binding) {
            return self::derive_bmff_hash_program($source, $source_size, $expected_size, $edits, $plan);
        }
        if ('c2pa.hash.data' !== $binding) {
            return new \WP_Error('plan_invalid', 'The signing plan uses an unsupported hard-binding algorithm.');
        }

        $authorized = self::authorize_data_edits($source, $source_size, $expected_size, $edits, $plan);
        if (is_wp_error($authorized)) {
            return $authorized;
        }

        $cursor = 0;
        $output_size = 0;
        $material_size = 0;
        $carrier_count = 0;
        $carrier_output_start = -1;
        $program = [];
        foreach ($edits as $edit) {
            if (! is_array($edit) || ! is_string($edit['op'] ?? null)) {
                return new \WP_Error('plan_invalid', 'The signing edit list is malformed.');
            }
            $offset = self::strict_nonnegative_int($edit['offset'] ?? null);
            if ('insert_carrier' === $edit['op']) {
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                $kind = 'insert';
                ++$carrier_count;
            } elseif ('delete' === $edit['op']) {
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                $kind = 'delete';
            } elseif ('patch' === $edit['op']) {
                $bytes = base64_decode((string) ($edit['b64'] ?? ''), true);
                $length = false === $bytes ? null : strlen($bytes);
                $kind = 'patch';
            } else {
                return new \WP_Error('plan_invalid', 'The signing edit list contains an unknown operation.');
            }
            if (null === $offset || null === $length || $length <= 0 || $offset < $cursor || $offset > $source_size) {
                return new \WP_Error('plan_invalid', 'A signing edit operation is out of order or out of bounds.');
            }
            $copy_length = $offset - $cursor;
            if ($copy_length > 0) {
                self::append_range_item($program, $cursor, $copy_length);
                $output_size += $copy_length;
                $material_size += $copy_length;
            }
            $cursor = $offset;
            if ('insert' === $kind) {
                $carrier_output_start = $output_size;
                $output_size += $length;
            } elseif ('delete' === $kind) {
                if ($cursor + $length > $source_size) {
                    return new \WP_Error('plan_invalid', 'A signing delete is out of bounds.');
                }
                $cursor += $length;
            } else {
                if ($cursor + $length > $source_size) {
                    return new \WP_Error('plan_invalid', 'A signing patch is out of bounds.');
                }
                $program[] = ['lit' => base64_encode($bytes)];
                $cursor += $length;
                $output_size += $length;
                $material_size += $length;
            }
        }
        $tail = $source_size - $cursor;
        if ($tail > 0) {
            self::append_range_item($program, $cursor, $tail);
            $output_size += $tail;
            $material_size += $tail;
        }
        $carrier_length = $output_size - $material_size;
        if (
            1 !== $carrier_count
            || $output_size !== $expected_size
            || $material_size <= 0
            || ($plan['carrier_span'] ?? null) !== ['offset' => 0, 'length' => $carrier_length]
            || ($plan['carrier_output_span'] ?? null) !== ['offset' => $carrier_output_start, 'length' => $carrier_length]
        ) {
            return new \WP_Error('plan_geometry_mismatch', 'The signing edits do not describe the complete output geometry.');
        }
        return $program;
    }
    /**
     * Require data-family edits to match geometry parsed from the locked source.
     *
     * Every advertised data-hash family is fail-closed. The MIME selected for
     * sparse planning is retained in the plan and selects one bounded parser.
     *
     * @return true|\WP_Error
     */
    private static function authorize_data_edits(
        $source,
        int $source_size,
        int $expected_size,
        array $edits,
        array $plan
    ) {
        $mime = $plan['mime'] ?? null;
        if (! is_string($mime) || '' === $mime) {
            return new \WP_Error('plan_invalid', 'The signing plan has no media type.');
        }
        $prefix_length = min(16, $source_size);
        if ($prefix_length <= 0) {
            return new \WP_Error('structure_invalid', 'The source media file is empty.');
        }
        $prefix = self::read_exact_at($source, 0, $prefix_length);
        if (is_wp_error($prefix)) {
            return $prefix;
        }
        $carrier_span = $plan['carrier_span'] ?? null;
        $carrier_length = is_array($carrier_span)
            ? self::strict_nonnegative_int($carrier_span['length'] ?? null)
            : null;
        if (
            null === $carrier_length
            || $carrier_length <= 0
            || $carrier_span !== ['offset' => 0, 'length' => $carrier_length]
        ) {
            return new \WP_Error('plan_geometry_mismatch', 'The signing plan has invalid carrier geometry.');
        }

        if (in_array($mime, ['image/jpeg', 'image/pjpeg'], true) && str_starts_with($prefix, "\xff\xd8")) {
            $geometry = self::derive_jpeg_edit_geometry($source, $source_size, $carrier_length);
        } elseif ('image/png' === $mime && str_starts_with($prefix, "\x89PNG\r\n\x1a\n")) {
            $geometry = self::derive_png_edit_geometry($source, $source_size, $carrier_length);
        } elseif (in_array($mime, ['audio/wav', 'image/webp', 'video/x-msvideo'], true) && str_starts_with($prefix, 'RIFF')) {
            $geometry = self::derive_riff_edit_geometry($source, $source_size, $carrier_length);
        } elseif (in_array($mime, ['image/tiff', 'image/x-adobe-dng'], true)) {
            $geometry = self::derive_tiff_edit_geometry($source, $source_size, $carrier_length);
        } elseif ('image/gif' === $mime) {
            $geometry = self::derive_gif_edit_geometry($source, $source_size, $carrier_length);
        } elseif ('image/svg+xml' === $mime) {
            $geometry = self::derive_svg_edit_geometry($source, $source_size, $carrier_length);
        } elseif ('audio/mpeg' === $mime) {
            $geometry = self::derive_id3_edit_geometry($source, $source_size, $carrier_length);
        } elseif ('audio/flac' === $mime) {
            $geometry = self::derive_flac_edit_geometry($source, $source_size, $carrier_length);
        } elseif ('audio/ogg' === $mime) {
            $geometry = self::derive_ogg_edit_geometry($source, $source_size, $carrier_length);
        } elseif ('image/jxl' === $mime) {
            $geometry = self::derive_jxl_edit_geometry($source, $source_size, $carrier_length);
        } else {
            return new \WP_Error('hash_mode_unsupported', 'The data-hash media format has no local edit authority.');
        }
        if (is_wp_error($geometry)) {
            return $geometry;
        }
        if (
            $edits !== $geometry['edits']
            || $expected_size !== $geometry['final_size']
            || ($plan['carrier_output_span'] ?? null) !== ['offset' => $geometry['output_start'], 'length' => $carrier_length]
        ) {
            return new \WP_Error('plan_geometry_mismatch', 'The signing edits do not match the locally parsed container geometry.');
        }
        return true;
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_jpeg_edit_geometry($source, int $source_size, int $carrier_length)
    {
        $geometry = HashMediaPlanner::jpeg_geometry($source, $source_size);
        if (is_wp_error($geometry)) {
            return $geometry;
        }
        if (count($geometry['deletes']) > 1) {
            return new \WP_Error('structure_invalid', 'Multiple JPEG C2PA carriers are ambiguous.');
        }
        return self::canonical_data_geometry(
            $source_size,
            $geometry['insert_at'],
            $carrier_length,
            $geometry['deletes'],
            []
        );
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_png_edit_geometry($source, int $source_size, int $carrier_length)
    {
        $position = 8;
        $insert_at = null;
        $deletes = [];
        $first = true;
        while ($position + 12 <= $source_size) {
            $header = self::read_exact_at($source, $position, 8);
            if (is_wp_error($header)) {
                return $header;
            }
            $length = unpack('Nlength', substr($header, 0, 4))['length'];
            $type = substr($header, 4, 4);
            $end = $position + 12 + $length;
            if ($end <= $position || $end > $source_size) {
                return new \WP_Error('structure_invalid', 'A PNG chunk is out of bounds.');
            }
            if ($first) {
                if ('IHDR' !== $type || 13 !== $length) {
                    return new \WP_Error('structure_invalid', 'The PNG does not begin with a canonical IHDR chunk.');
                }
                $first = false;
            }
            if ('caBX' === $type) {
                $valid = HashMediaPlanner::validate_store_payload(
                    $source,
                    $position + 8,
                    $length,
                    'PNG'
                );
                if (is_wp_error($valid)) {
                    return $valid;
                }
                $deletes[] = [$position, $end - $position];
            }
            if ('IEND' === $type) {
                if (0 !== $length || $end !== $source_size) {
                    return new \WP_Error('structure_invalid', 'The PNG IEND geometry is invalid.');
                }
                if (count($deletes) > 1) {
                    return new \WP_Error('structure_invalid', 'Multiple PNG C2PA carriers are ambiguous.');
                }
                return self::canonical_data_geometry($source_size, $position, $carrier_length, $deletes, []);
            }
            $position = $end;
        }
        return new \WP_Error('structure_invalid', 'The PNG chunk table has no complete IEND chunk.');
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_riff_edit_geometry($source, int $source_size, int $carrier_length)
    {
        if ($source_size < 12 || 0 !== ($source_size & 1) || $carrier_length < 8 || 0 !== ($carrier_length & 1)) {
            return new \WP_Error('structure_invalid', 'The RIFF carrier alignment is invalid.');
        }
        $header = self::read_exact_at($source, 0, 12);
        if (is_wp_error($header)) {
            return $header;
        }
        $declared_size = unpack('Vsize', substr($header, 4, 4))['size'];
        if ($declared_size !== $source_size - 8) {
            return new \WP_Error('structure_invalid', 'The RIFF size field does not match the local file.');
        }
        $position = 12;
        $deletes = [];
        while ($position + 8 <= $source_size) {
            $chunk = self::read_exact_at($source, $position, 8);
            if (is_wp_error($chunk)) {
                return $chunk;
            }
            $length = unpack('Vlength', substr($chunk, 4, 4))['length'];
            $padded = $length + ($length & 1);
            $end = $position + 8 + $padded;
            if ($end <= $position || $end > $source_size) {
                return new \WP_Error('structure_invalid', 'A RIFF chunk is out of bounds.');
            }
            if ('C2PA' === substr($chunk, 0, 4)) {
                $valid = HashMediaPlanner::validate_store_payload(
                    $source,
                    $position + 8,
                    $length,
                    'RIFF'
                );
                if (is_wp_error($valid)) {
                    return $valid;
                }
                $deletes[] = [$position, $end - $position];
            }
            $position = $end;
        }
        if ($position !== $source_size) {
            return new \WP_Error('structure_invalid', 'The RIFF chunk table has a coverage gap.');
        }
        if (count($deletes) > 1) {
            return new \WP_Error('structure_invalid', 'Multiple RIFF C2PA carriers are ambiguous.');
        }
        $removed = array_sum(array_column($deletes, 1));
        $final_size = $source_size - $removed + $carrier_length;
        if ($final_size < 8 || $final_size - 8 > 0xffffffff) {
            return new \WP_Error('structure_invalid', 'The signed RIFF size is out of range.');
        }
        return self::canonical_data_geometry(
            $source_size,
            $source_size,
            $carrier_length,
            $deletes,
            [[4, pack('V', $final_size - 8)]]
        );
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_tiff_edit_geometry($source, int $source_size, int $carrier_length)
    {
        if ($source_size < 8) {
            return new \WP_Error('structure_invalid', 'The TIFF header is truncated.');
        }
        $header = self::read_exact_at($source, 0, 8);
        if (is_wp_error($header)) {
            return $header;
        }
        $little = 'II' === substr($header, 0, 2);
        if (! $little && 'MM' !== substr($header, 0, 2)) {
            return new \WP_Error('structure_invalid', 'The TIFF byte order is invalid.');
        }
        $u16 = static fn(string $bytes): int => unpack($little ? 'v' : 'n', $bytes)[1];
        $u32 = static fn(string $bytes): int => unpack($little ? 'V' : 'N', $bytes)[1];
        if (42 !== $u16(substr($header, 2, 2))) {
            return new \WP_Error('structure_invalid', 'The TIFF magic is invalid.');
        }
        $ifd = $u32(substr($header, 4, 4));
        $visited = [];
        $first_entries = 0;
        $manifest_count = 0;
        while (0 !== $ifd) {
            if (isset($visited[$ifd]) || count($visited) >= 64 || $ifd + 2 > $source_size) {
                return new \WP_Error('structure_invalid', 'The TIFF IFD chain is invalid.');
            }
            $visited[$ifd] = true;
            $count_bytes = self::read_exact_at($source, $ifd, 2);
            if (is_wp_error($count_bytes)) {
                return $count_bytes;
            }
            $count = $u16($count_bytes);
            $length = 2 + 12 * $count + 4;
            if ($count > self::MAX_PLAN_ITEMS || $ifd + $length > $source_size) {
                return new \WP_Error('structure_invalid', 'A TIFF IFD is out of bounds.');
            }
            $table = self::read_exact_at($source, $ifd + 2, $length - 2);
            if (is_wp_error($table)) {
                return $table;
            }
            $kept = 0;
            for ($index = 0; $index < $count; ++$index) {
                $entry = substr($table, 12 * $index, 12);
                if (0xcd41 !== $u16(substr($entry, 0, 2))) {
                    ++$kept;
                    continue;
                }
                ++$manifest_count;
                if ($manifest_count > 1) {
                    return new \WP_Error('structure_invalid', 'Multiple TIFF C2PA carriers are ambiguous.');
                }
                if (1 !== count($visited)) {
                    return new \WP_Error('structure_invalid', 'A TIFF manifest outside the first IFD cannot be replaced safely.');
                }
                $store_length = $u32(substr($entry, 4, 4));
                $store_offset = $store_length <= 4 ? $ifd + 2 + 12 * $index + 8 : $u32(substr($entry, 8, 4));
                $valid = HashMediaPlanner::validate_store_payload($source, $store_offset, $store_length, 'TIFF');
                if (is_wp_error($valid)) {
                    return $valid;
                }
            }
            if (1 === count($visited)) {
                $first_entries = $kept;
            }
            $ifd = $u32(substr($table, 12 * $count, 4));
        }
        $ifd_length = 2 + 12 * ($first_entries + 1) + 4;
        if ($carrier_length < $ifd_length || $source_size + $carrier_length - $ifd_length > 0xffffffff) {
            return new \WP_Error('structure_invalid', 'The TIFF carrier geometry is invalid.');
        }
        $new_ifd = $source_size + $carrier_length - $ifd_length;
        return self::canonical_data_geometry(
            $source_size,
            $source_size,
            $carrier_length,
            [],
            [[4, pack($little ? 'V' : 'N', $new_ifd)]]
        );
    }

    /** @return int|\WP_Error */
    private static function gif_subblocks_end($source, int $position, int $source_size)
    {
        for ($items = 0; $items < self::MAX_PLAN_ITEMS; ++$items) {
            if ($position >= $source_size) {
                return new \WP_Error('structure_invalid', 'A GIF sub-block is truncated.');
            }
            $byte = self::read_exact_at($source, $position, 1);
            if (is_wp_error($byte)) {
                return $byte;
            }
            $length = ord($byte);
            ++$position;
            if (0 === $length) {
                return $position;
            }
            if ($position + $length > $source_size) {
                return new \WP_Error('structure_invalid', 'A GIF sub-block is out of bounds.');
            }
            $position += $length;
        }
        return new \WP_Error('structure_invalid', 'The GIF contains too many sub-blocks.');
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_gif_edit_geometry($source, int $source_size, int $carrier_length)
    {
        $header = self::read_exact_at($source, 0, min(13, $source_size));
        if (is_wp_error($header) || 13 !== strlen($header) || ! in_array(substr($header, 0, 6), ['GIF87a', 'GIF89a'], true)) {
            return new \WP_Error('structure_invalid', 'The GIF signature is invalid.');
        }
        $position = 13 + (0 !== (ord($header[10]) & 0x80) ? 3 * (1 << ((ord($header[10]) & 7) + 1)) : 0);
        if ($position > $source_size) {
            return new \WP_Error('structure_invalid', 'The GIF global color table is out of bounds.');
        }
        $insert_at = $position;
        $deletes = [];
        for ($items = 0; $position < $source_size && $items < self::MAX_PLAN_ITEMS; ++$items) {
            $kind = self::read_exact_at($source, $position, 1);
            if (is_wp_error($kind)) {
                return $kind;
            }
            if ("\x3b" === $kind) {
                if (count($deletes) > 1) {
                    return new \WP_Error('structure_invalid', 'Multiple GIF C2PA carriers are ambiguous.');
                }
                return $position + 1 === $source_size
                    ? self::canonical_data_geometry($source_size, $insert_at, $carrier_length, $deletes, [])
                    : new \WP_Error('structure_invalid', 'Bytes follow the GIF trailer.');
            }
            $start = $position;
            if ("\x21" === $kind) {
                $prefix = self::read_exact_at($source, $position, 3);
                if (is_wp_error($prefix)) {
                    return $prefix;
                }
                $label = ord($prefix[1]);
                if (in_array($label, [0xff, 0x01], true)) {
                    $expected = 0xff === $label ? 11 : 12;
                    if (ord($prefix[2]) !== $expected) {
                        return new \WP_Error('structure_invalid', 'A GIF extension header length is invalid.');
                    }
                    $app = self::read_exact_at($source, $position, 3 + $expected);
                    if (is_wp_error($app)) {
                        return $app;
                    }
                    $position += 3 + $expected;
                    $end = self::gif_subblocks_end($source, $position, $source_size);
                    if (is_wp_error($end)) {
                        return $end;
                    }
                    if (0xff === $label && 'C2PA_GIF' . "\x01\x00\x00" === substr($app, 3, 11)) {
                        $payload = self::collect_gif_subblocks($source, $position, $end);
                        if (is_wp_error($payload)) {
                            return $payload;
                        }
                        $valid = self::validate_store_bytes($payload, 'GIF');
                        if (is_wp_error($valid)) {
                            return $valid;
                        }
                        $deletes[] = [$start, $end - $start];
                    }
                    $position = $end;
                } elseif (0xfe === $label) {
                    $position = self::gif_subblocks_end($source, $position + 2, $source_size);
                } elseif (0xf9 === $label) {
                    $control = self::read_exact_at($source, $position, 8);
                    if (is_wp_error($control) || 4 !== ord($control[2]) || "\0" !== $control[7]) {
                        return new \WP_Error('structure_invalid', 'A GIF graphics control extension is invalid.');
                    }
                    $position += 8;
                } else {
                    return new \WP_Error('structure_invalid', 'The GIF contains an unknown extension.');
                }
            } elseif ("\x2c" === $kind) {
                $descriptor = self::read_exact_at($source, $position, 10);
                if (is_wp_error($descriptor)) {
                    return $descriptor;
                }
                $position += 10;
                if (0 !== (ord($descriptor[9]) & 0x80)) {
                    $position += 3 * (1 << ((ord($descriptor[9]) & 7) + 1));
                }
                if ($position >= $source_size) {
                    return new \WP_Error('structure_invalid', 'The GIF image data is truncated.');
                }
                $position = self::gif_subblocks_end($source, $position + 1, $source_size);
            } else {
                return new \WP_Error('structure_invalid', 'The GIF block table is invalid.');
            }
            if (is_wp_error($position)) {
                return $position;
            }
        }
        return new \WP_Error('structure_invalid', 'The GIF trailer is missing.');
    }

    /** @return string|\WP_Error */
    private static function collect_gif_subblocks($source, int $position, int $end)
    {
        $payload = '';
        while ($position < $end) {
            $length_byte = self::read_exact_at($source, $position, 1);
            if (is_wp_error($length_byte)) {
                return $length_byte;
            }
            $length = ord($length_byte);
            ++$position;
            if (0 === $length) {
                return $position === $end ? $payload : new \WP_Error('structure_invalid', 'The GIF carrier terminator is misplaced.');
            }
            $part = self::read_exact_at($source, $position, $length);
            if (is_wp_error($part)) {
                return $part;
            }
            $payload .= $part;
            $position += $length;
        }
        return new \WP_Error('structure_invalid', 'The GIF carrier has no terminator.');
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_svg_edit_geometry($source, int $source_size, int $carrier_length)
    {
        if ($source_size > 33_554_432) {
            return new \WP_Error('structure_too_large', 'The SVG structure exceeds the local parser limit.');
        }
        $text = self::read_exact_at($source, 0, $source_size);
        if (is_wp_error($text) || 1 !== preg_match('//u', $text)) {
            return new \WP_Error('structure_invalid', 'The SVG is not valid UTF-8.');
        }
        $root = strpos($text, '<svg');
        $root_end = false === $root ? false : strpos($text, '>', $root);
        if (false === $root || false === $root_end) {
            return new \WP_Error('structure_invalid', 'The SVG root element is missing or unterminated.');
        }
        $spans = [];
        $element_open = '<metadata><c2pa:manifest xmlns:c2pa="http://c2pa.org/manifest">';
        $element_close = '</c2pa:manifest></metadata>';
        $position = 0;
        while (false !== ($start = strpos($text, $element_open, $position))) {
            $content = $start + strlen($element_open);
            $close = strpos($text, $element_close, $content);
            if (false === $close) {
                return new \WP_Error('structure_invalid', 'The SVG manifest element is unterminated.');
            }
            $encoded = substr($text, $content, $close - $content);
            $store = base64_decode($encoded, true);
            if (false === $store || base64_encode($store) !== $encoded || is_wp_error(self::validate_store_bytes($store, 'SVG'))) {
                return new \WP_Error('structure_invalid', 'The SVG manifest element is malformed.');
            }
            $end = $close + strlen($element_close);
            $spans[] = [$start, $end - $start];
            $position = $end;
        }
        if (count($spans) > 1) {
            return new \WP_Error('structure_invalid', 'The SVG contains multiple manifest carriers.');
        }
        return self::canonical_data_geometry($source_size, $root_end + 1, $carrier_length, $spans, []);
    }

    /** @return int|\WP_Error */
    private static function id3_prefix_length($source, int $source_size)
    {
        if ($source_size < 3) {
            return 0;
        }
        $prefix = self::read_exact_at($source, 0, min(10, $source_size));
        if (is_wp_error($prefix)) {
            return $prefix;
        }
        if ('ID3' !== substr($prefix, 0, 3)) {
            return 0;
        }
        if (10 !== strlen($prefix) || ! in_array(ord($prefix[3]), [3, 4], true)) {
            return new \WP_Error('structure_invalid', 'The ID3 header is invalid.');
        }
        $size = 0;
        for ($index = 6; $index < 10; ++$index) {
            $byte = ord($prefix[$index]);
            if (0 !== ($byte & 0x80)) {
                return new \WP_Error('structure_invalid', 'The ID3 size is not synchsafe.');
            }
            $size = ($size << 7) | $byte;
        }
        $length = 10 + $size + (4 === ord($prefix[3]) && 0 !== (ord($prefix[5]) & 0x10) ? 10 : 0);
        return $length <= $source_size ? $length : new \WP_Error('structure_invalid', 'The ID3 tag is out of bounds.');
    }

    /**
     * @return array{tag_length:int,insert_at:int,deletes:array<int,array{0:int,1:int}>,patches:array<int,array{0:int,1:string}>}|\WP_Error
     */
    private static function derive_id3_edit_parts($source, int $source_size, int $carrier_length)
    {
        $tag_length = self::id3_prefix_length($source, $source_size);
        if (is_wp_error($tag_length) || 0 === $tag_length) {
            return is_wp_error($tag_length)
                ? $tag_length
                : ['tag_length' => 0, 'insert_at' => 0, 'deletes' => [], 'patches' => []];
        }
        $header = self::read_exact_at($source, 0, 10);
        if (is_wp_error($header)) {
            return $header;
        }
        $major = ord($header[3]);
        $flags = ord($header[5]);
        if (0 !== ($flags & 0xc0)) {
            return new \WP_Error('structure_invalid', 'ID3 unsynchronization and extended headers are not supported.');
        }
        $body_length = 0;
        for ($index = 6; $index < 10; ++$index) {
            $body_length = ($body_length << 7) | ord($header[$index]);
        }
        $body_end = 10 + $body_length;
        $position = 10;
        $deletes = [];
        $removed_body = 0;
        $found = false;
        while ($position < $body_end) {
            $first = self::read_exact_at($source, $position, 1);
            if (is_wp_error($first)) {
                return $first;
            }
            if ("\0" === $first) {
                $padding = self::read_exact_at($source, $position, $body_end - $position);
                if (is_wp_error($padding) || trim($padding, "\0") !== '') {
                    return new \WP_Error('structure_invalid', 'The ID3 padding contains nonzero bytes.');
                }
                $deletes[] = [$position, $body_end - $position];
                $removed_body += $body_end - $position;
                $position = $body_end;
                break;
            }
            if ($position + 10 > $body_end) {
                return new \WP_Error('structure_invalid', 'An ID3 frame header is truncated.');
            }
            $frame = self::read_exact_at($source, $position, 10);
            if (is_wp_error($frame)) {
                return $frame;
            }
            if (4 === $major) {
                $frame_length = 0;
                for ($index = 4; $index < 8; ++$index) {
                    $byte = ord($frame[$index]);
                    if (0 !== ($byte & 0x80)) {
                        return new \WP_Error('structure_invalid', 'An ID3v2.4 frame size is not synchsafe.');
                    }
                    $frame_length = ($frame_length << 7) | $byte;
                }
            } else {
                $frame_length = unpack('N', substr($frame, 4, 4))[1];
            }
            $frame_end = $position + 10 + $frame_length;
            if ($frame_end > $body_end) {
                return new \WP_Error('structure_invalid', 'An ID3 frame is out of bounds.');
            }
            if ('GEOB' === substr($frame, 0, 4) && $frame_length >= 18) {
                $prefix = self::read_exact_at($source, $position + 10, 18);
                if (! is_wp_error($prefix) && "\0application/c2pa\0" === $prefix) {
                    if ($found) {
                        return new \WP_Error('structure_invalid', 'The ID3 tag has multiple C2PA frames.');
                    }
                    $payload = self::read_exact_at($source, $position + 10, $frame_length);
                    $store = is_wp_error($payload) ? $payload : self::extract_id3_geob_store($payload);
                    if (is_wp_error($store) || is_wp_error(self::validate_store_bytes($store, 'ID3'))) {
                        return new \WP_Error('structure_invalid', 'The ID3 C2PA frame is malformed.');
                    }
                    $deletes[] = [$position, $frame_end - $position];
                    $removed_body += $frame_end - $position;
                    $found = true;
                }
            }
            $position = $frame_end;
        }
        $patches = [];
        if (4 === $major && 0 !== ($flags & 0x10)) {
            $footer = self::read_exact_at($source, $body_end, 10);
            if (is_wp_error($footer) || '3DI' !== substr($footer, 0, 3)) {
                return new \WP_Error('structure_invalid', 'The ID3 footer is malformed.');
            }
            $deletes[] = [$body_end, 10];
            $patches[] = [5, chr($flags & ~0x10)];
        }
        $new_body_length = $body_length - $removed_body + $carrier_length;
        if ($new_body_length > 0x0fffffff) {
            return new \WP_Error('structure_invalid', 'The ID3 tag exceeds the synchsafe size limit.');
        }
        $patches[] = [6, self::synchsafe_id3_bytes($new_body_length)];
        return [
            'tag_length' => $tag_length,
            'insert_at' => $body_end,
            'deletes' => $deletes,
            'patches' => $patches,
        ];
    }

    private static function synchsafe_id3_bytes(int $size): string
    {
        return chr(($size >> 21) & 0x7f)
            . chr(($size >> 14) & 0x7f)
            . chr(($size >> 7) & 0x7f)
            . chr($size & 0x7f);
    }

    /** @return string|\WP_Error */
    private static function extract_id3_geob_store(string $payload)
    {
        if ('' === $payload || "\0" !== $payload[0]) {
            return new \WP_Error('structure_invalid', 'The ID3 GEOB encoding is unsupported.');
        }
        $position = 1;
        for ($field = 0; $field < 3; ++$field) {
            $end = strpos($payload, "\0", $position);
            if (false === $end) {
                return new \WP_Error('structure_invalid', 'The ID3 GEOB fields are unterminated.');
            }
            if (0 === $field && 'application/c2pa' !== substr($payload, $position, $end - $position)) {
                return new \WP_Error('structure_invalid', 'The ID3 GEOB MIME type is invalid.');
            }
            $position = $end + 1;
        }
        return substr($payload, $position);
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_id3_edit_geometry($source, int $source_size, int $carrier_length)
    {
        $parts = self::derive_id3_edit_parts($source, $source_size, $carrier_length);
        if (is_wp_error($parts)) {
            return $parts;
        }
        return self::canonical_data_geometry(
            $source_size,
            $parts['insert_at'],
            $carrier_length,
            $parts['deletes'],
            $parts['patches']
        );
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_flac_edit_geometry($source, int $source_size, int $carrier_length)
    {
        $id3_parts = self::derive_id3_edit_parts($source, $source_size, $carrier_length);
        if (is_wp_error($id3_parts)) {
            return $id3_parts;
        }
        $id3 = $id3_parts['tag_length'];
        $magic = self::read_exact_at($source, $id3, 4);
        if (is_wp_error($magic) || 'fLaC' !== $magic) {
            return new \WP_Error('structure_invalid', 'The FLAC signature is invalid.');
        }
        $position = $id3 + 4;
        $deletes = $id3_parts['deletes'];
        $patches = $id3_parts['patches'];
        $manifest_blocks = 0;
        for ($items = 0; $items < self::MAX_PLAN_ITEMS; ++$items) {
            $header = self::read_exact_at($source, $position, 4);
            if (is_wp_error($header)) {
                return $header;
            }
            $length = (ord($header[1]) << 16) | (ord($header[2]) << 8) | ord($header[3]);
            $end = $position + 4 + $length;
            if ($end > $source_size) {
                return new \WP_Error('structure_invalid', 'A FLAC metadata block is out of bounds.');
            }
            $kind = ord($header[0]) & 0x7f;
            $is_c2pa = 2 === $kind && $length >= 4 && 'c2pa' === self::read_exact_at($source, $position + 4, 4);
            if ($is_c2pa) {
                $valid = HashMediaPlanner::validate_store_payload($source, $position + 8, $length - 4, 'FLAC');
                if (is_wp_error($valid)) {
                    return $valid;
                }
                $deletes[] = [$position, 4 + $length];
                ++$manifest_blocks;
                if ($manifest_blocks > 1) {
                    return new \WP_Error('structure_invalid', 'Multiple FLAC C2PA carriers are ambiguous.');
                }
            } else {
                $kept[] = [$position, ord($header[0])];
            }
            $position = $end;
            if (0 !== (ord($header[0]) & 0x80)) {
                break;
            }
        }
        if ([] === $kept) {
            return new \WP_Error('structure_invalid', 'The FLAC has no retained metadata block.');
        }
        $flac_patches = [];
        foreach ($kept as $index => [$offset, $old]) {
            $new = $index + 1 === count($kept) ? $old | 0x80 : $old & 0x7f;
            if ($new !== $old) {
                $flac_patches[] = [$offset, chr($new)];
            }
        }
        return self::canonical_data_geometry(
            $source_size,
            $id3_parts['insert_at'],
            $carrier_length,
            $deletes,
            array_merge($patches, $flac_patches)
        );
    }

    /** @return array<int,array<string,mixed>>|\WP_Error */
    private static function parse_ogg_pages($source, int $source_size, bool $validate_checksum = false)
    {
        $pages = [];
        $position = 0;
        while ($position < $source_size && count($pages) < self::MAX_PLAN_ITEMS) {
            $fixed = self::read_exact_at($source, $position, 27);
            if (is_wp_error($fixed) || 'OggS' !== substr($fixed, 0, 4) || "\0" !== $fixed[4]) {
                return new \WP_Error('structure_invalid', 'An Ogg page header is invalid.');
            }
            $lace_count = ord($fixed[26]);
            $laces = self::read_exact_at($source, $position + 27, $lace_count);
            if (is_wp_error($laces)) {
                return $laces;
            }
            $body_length = 0;
            for ($index = 0; $index < $lace_count; ++$index) {
                $body_length += ord($laces[$index]);
            }
            $body = $position + 27 + $lace_count;
            $end = $body + $body_length;
            if ($end > $source_size) {
                return new \WP_Error('structure_invalid', 'An Ogg page is out of bounds.');
            }
            if ($validate_checksum) {
                $page = self::read_exact_at($source, $position, $end - $position);
                if (is_wp_error($page)) {
                    return $page;
                }
                $declared_crc = unpack('V', substr($page, 22, 4))[1];
                $page = substr_replace($page, "\0\0\0\0", 22, 4);
                if ($declared_crc !== self::ogg_crc($page)) {
                    return new \WP_Error('structure_invalid', 'An Ogg page checksum is invalid.');
                }
            }
            $pages[] = [
                'start' => $position,
                'end' => $end,
                'type' => ord($fixed[5]),
                'serial' => unpack('V', substr($fixed, 14, 4))[1],
                'laces' => $laces,
                'body' => $body,
                'sequence' => unpack('V', substr($fixed, 18, 4))[1],
            ];
            $position = $end;
        }
        return $position === $source_size && [] !== $pages
            ? $pages
            : new \WP_Error('structure_invalid', 'The Ogg page table is incomplete.');
    }

    private static function ogg_crc(string $bytes): int
    {
        $crc = 0;
        for ($index = 0, $length = strlen($bytes); $index < $length; ++$index) {
            $crc ^= ord($bytes[$index]) << 24;
            for ($bit = 0; $bit < 8; ++$bit) {
                $crc = 0 !== ($crc & 0x80000000)
                    ? (($crc << 1) ^ 0x04c11db7) & 0xffffffff
                    : ($crc << 1) & 0xffffffff;
            }
        }
        return $crc;
    }
    /** @return array<int,string>|\WP_Error */
    private static function validate_ogg_streams($source, array $pages)
    {
        $streams = [];
        foreach ($pages as $page) {
            $serial = (int) $page['serial'];
            $type = (int) $page['type'];
            $sequence = (int) $page['sequence'];
            $laces = (string) $page['laces'];
            if (0 !== ($type & ~0x07) || '' === $laces) {
                return new \WP_Error('structure_invalid', 'An Ogg page has invalid flags or lacing values.');
            }
            if (! isset($streams[$serial])) {
                if (0 !== $sequence || 0 === ($type & 0x02) || 0 !== ($type & 0x01)) {
                    return new \WP_Error('structure_invalid', 'An Ogg logical stream has an invalid first page.');
                }
                $streams[$serial] = [
                    'last_sequence' => null,
                    'packet_open' => false,
                    'packet_count' => 0,
                    'eos' => false,
                ];
            } else {
                $previous = $streams[$serial]['last_sequence'];
                if (0xffffffff === $previous || $sequence !== $previous + 1) {
                    return new \WP_Error('structure_invalid', 'An Ogg logical stream page sequence is invalid.');
                }
                if ($streams[$serial]['eos']) {
                    return new \WP_Error('structure_invalid', 'An Ogg page follows the end of its logical stream.');
                }
                if (0 !== ($type & 0x02)) {
                    return new \WP_Error('structure_invalid', 'A later Ogg page repeats the BOS flag.');
                }
                if ((0 !== ($type & 0x01)) !== $streams[$serial]['packet_open']) {
                    return new \WP_Error('structure_invalid', 'An Ogg packet continuation flag is invalid.');
                }
            }
            for ($index = 0, $count = strlen($laces); $index < $count; ++$index) {
                if (ord($laces[$index]) < 255) {
                    ++$streams[$serial]['packet_count'];
                    $streams[$serial]['packet_open'] = false;
                } else {
                    $streams[$serial]['packet_open'] = true;
                }
            }
            if (0 !== ($type & 0x04)) {
                if ($streams[$serial]['packet_open']) {
                    return new \WP_Error('structure_invalid', 'An Ogg stream ends without a packet terminator.');
                }
                $streams[$serial]['eos'] = true;
            }
            $streams[$serial]['last_sequence'] = $sequence;
        }

        $packets = [];
        $manifest_serial = null;
        foreach ($streams as $serial => $state) {
            if (! $state['eos']) {
                return new \WP_Error('structure_invalid', 'An Ogg logical stream has no EOS page.');
            }
            $packet = self::ogg_first_packet($source, $pages, (int) $serial);
            if (is_wp_error($packet)) {
                return $packet;
            }
            $packets[(int) $serial] = $packet;
            if (str_starts_with($packet, "\0c2pa")) {
                if (null !== $manifest_serial) {
                    return new \WP_Error('structure_invalid', 'Multiple Ogg C2PA streams are ambiguous.');
                }
                if (1 !== $state['packet_count']) {
                    return new \WP_Error('structure_invalid', 'Material follows an Ogg C2PA packet.');
                }
                $manifest_serial = $serial;
            }
        }
        return $packets;
    }

    /** @return string|\WP_Error */
    private static function ogg_first_packet($source, array $pages, int $serial)
    {
        $packet = '';
        foreach ($pages as $page) {
            if ($page['serial'] !== $serial) {
                continue;
            }
            $position = $page['body'];
            for ($index = 0, $count = strlen($page['laces']); $index < $count; ++$index) {
                $length = ord($page['laces'][$index]);
                if ($length > 0) {
                    $part = self::read_exact_at($source, $position, $length);
                    if (is_wp_error($part)) {
                        return $part;
                    }
                    $packet .= $part;
                }
                $position += $length;
                if ($length < 255) {
                    return $packet;
                }
            }
        }
        return new \WP_Error('structure_invalid', 'An Ogg first packet is unterminated.');
    }
    /** @return string|\WP_Error */
    private static function extract_strict_ogg_carrier($source, array $pages)
    {
        if ([] === $pages || 1 !== count(array_unique(array_column($pages, 'serial')))) {
            return new \WP_Error('carrier_structure_mismatch', 'The returned Ogg carrier must contain one logical stream.');
        }
        $packet = '';
        $last_page = count($pages) - 1;
        foreach ($pages as $page_index => $page) {
            $type = (int) $page['type'];
            if (
                0 !== ($type & ~0x07)
                || (int) $page['sequence'] !== $page_index
                || (0 === $page_index && (0 === ($type & 0x02) || 0 !== ($type & 0x01)))
                || (0 < $page_index && (0 !== ($type & 0x02) || 0 === ($type & 0x01)))
                || ($page_index < $last_page && 0 !== ($type & 0x04))
                || ($page_index === $last_page && 0 === ($type & 0x04))
                || '' === $page['laces']
            ) {
                return new \WP_Error('carrier_structure_mismatch', 'The returned Ogg carrier page sequence is invalid.');
            }
            $body_position = (int) $page['body'];
            $lace_count = strlen($page['laces']);
            for ($lace_index = 0; $lace_index < $lace_count; ++$lace_index) {
                $length = ord($page['laces'][$lace_index]);
                $is_final_lace = $page_index === $last_page && $lace_index + 1 === $lace_count;
                if ((! $is_final_lace && 255 !== $length) || ($is_final_lace && 255 === $length)) {
                    return new \WP_Error('carrier_structure_mismatch', 'The returned Ogg carrier must contain exactly one terminated packet.');
                }
                if ($length > 0) {
                    $part = self::read_exact_at($source, $body_position, $length);
                    if (is_wp_error($part)) {
                        return new \WP_Error('carrier_structure_mismatch', 'The returned Ogg carrier packet is incomplete.');
                    }
                    $packet .= $part;
                }
                $body_position += $length;
            }
        }
        return str_starts_with($packet, "\0c2pa")
            ? substr($packet, 5)
            : new \WP_Error('carrier_structure_mismatch', 'The returned Ogg carrier packet is invalid.');
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_ogg_edit_geometry($source, int $source_size, int $carrier_length)
    {
        $pages = self::parse_ogg_pages($source, $source_size, true);
        if (is_wp_error($pages)) {
            return $pages;
        }
        $packets = self::validate_ogg_streams($source, $pages);
        if (is_wp_error($packets)) {
            return $packets;
        }
        $manifest_serials = [];
        foreach ($packets as $serial => $packet) {
            if (str_starts_with($packet, "\0c2pa")) {
                $store = substr($packet, 5);
                $valid = self::validate_store_bytes($store, 'Ogg');
                if (is_wp_error($valid)) {
                    return $valid;
                }
                $manifest_serials[$serial] = true;
            }
        }
        $insert_at = $source_size;
        foreach ($pages as $page) {
            if (0 === ($page['type'] & 2)) {
                $insert_at = $page['start'];
                break;
            }
        }
        $deletes = [];
        foreach ($pages as $page) {
            if (isset($manifest_serials[$page['serial']])) {
                $deletes[] = [$page['start'], $page['end'] - $page['start']];
            }
        }
        return self::canonical_data_geometry($source_size, $insert_at, $carrier_length, $deletes, []);
    }

    /** @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}|\WP_Error */
    private static function derive_jxl_edit_geometry($source, int $source_size, int $carrier_length)
    {
        $boxes = self::parse_bmff_top_boxes($source, $source_size, false);
        if (is_wp_error($boxes) || [] === $boxes || 'JXL ' !== $boxes[0]['type']) {
            return new \WP_Error('structure_invalid', 'The JXL signature box is missing.');
        }
        $insert_at = $boxes[0]['end'];
        $deletes = [];
        foreach ($boxes as $box) {
            if ('ftyp' === $box['type']) {
                $insert_at = $box['end'];
                break;
            }
        }
        foreach ($boxes as $box) {
            if ('jumb' !== $box['type']) {
                continue;
            }
            $is_store = HashMediaPlanner::store_payload_is_complete(
                $source,
                $box['start'],
                $box['end'] - $box['start']
            );
            if (is_wp_error($is_store)) {
                return $is_store;
            }
            if ($is_store) {
                $deletes[] = [$box['start'], $box['end'] - $box['start']];
            }
        }
        if (count($deletes) > 1) {
            return new \WP_Error('structure_invalid', 'Multiple JXL C2PA carriers are ambiguous.');
        }
        return self::canonical_data_geometry($source_size, $insert_at, $carrier_length, $deletes, []);
    }

    /** @return array{0:string,1:string}|\WP_Error */
    private static function decode_finalize_material(array $result, array $plan)
    {
        $carrier_encoded = $result['carrier_b64'] ?? null;
        $manifest_encoded = $result['manifest_store_b64'] ?? null;
        $expected_manifest_size = self::strict_nonnegative_int($plan['expected_manifest_size'] ?? null);
        if (
            ! is_string($carrier_encoded)
            || ! is_string($manifest_encoded)
            || '' === $carrier_encoded
            || '' === $manifest_encoded
            || strlen($carrier_encoded) > 4 * intdiv(self::MAX_CARRIER_BYTES + 2, 3)
            || strlen($manifest_encoded) > 4 * intdiv(self::MAX_MANIFEST_BYTES + 2, 3)
            || null === $expected_manifest_size
            || $expected_manifest_size <= 0
            || $expected_manifest_size > self::MAX_MANIFEST_BYTES
        ) {
            return new \WP_Error('finalize_too_large', 'The signing service returned oversized manifest material.');
        }
        $carrier = base64_decode($carrier_encoded, true);
        $manifest = base64_decode($manifest_encoded, true);
        if (
            false === $carrier
            || false === $manifest
            || '' === $carrier
            || '' === $manifest
            || strlen($carrier) > self::MAX_CARRIER_BYTES
            || strlen($manifest) > self::MAX_MANIFEST_BYTES
            || strlen($manifest) !== $expected_manifest_size
        ) {
            return new \WP_Error('finalize_invalid', 'The signing service returned invalid manifest material.');
        }
        return [$carrier, $manifest];
    }

    /** @return true|\WP_Error */
    private static function validate_finalize_result(
        array $result,
        array $plan,
        string $digest,
        string $carrier,
        string $manifest,
        $source
    ) {
        if (
            ! is_string($result['carrier_b64'] ?? null)
            || ! is_string($result['manifest_store_b64'] ?? null)
            || base64_encode($carrier) !== $result['carrier_b64']
            || base64_encode($manifest) !== $result['manifest_store_b64']
        ) {
            return new \WP_Error('finalize_invalid', 'The signing service returned noncanonical base64 material.');
        }
        $manifest_hash = hash('sha256', $manifest);
        $carrier_hash = hash('sha256', $carrier);
        $binding = $result['binding'] ?? null;
        if (
            ($result['binding_algorithm'] ?? null) !== ($plan['binding_algorithm'] ?? 'c2pa.hash.data')
            || ($result['binding_commitment'] ?? null) !== $digest
            || ! is_array($binding)
            || ($binding['digest'] ?? null) !== $digest
            || ($result['manifest_sha256'] ?? null) !== $manifest_hash
            || ($result['carrier_sha256'] ?? null) !== $carrier_hash
            || ($result['expected_final_size'] ?? null) !== ($plan['expected_final_size'] ?? null)
        ) {
            return new \WP_Error('finalize_mismatch', 'The signing service finalize response does not match the prepared commitment.');
        }
        $expected_type = 'c2pa.hash.bmff.v3' === ($plan['binding_algorithm'] ?? null) ? 'bmff_hash' : 'data_hash';
        if (($binding['type'] ?? null) !== $expected_type) {
            return new \WP_Error('finalize_mismatch', 'The signing service returned the wrong hard-binding type.');
        }
        $store_valid = self::validate_store_bytes($manifest, 'returned');
        if (is_wp_error($store_valid)) {
            return new \WP_Error('finalize_invalid', 'The signing service returned an invalid manifest store.');
        }
        return self::validate_carrier_manifest((string) ($plan['mime'] ?? ''), $carrier, $manifest, $plan, $source);
    }

    private static function validate_carrier_manifest(string $mime, string $carrier, string $manifest, array $plan, $source = null)
    {
        if (in_array($mime, ['image/jpeg', 'image/pjpeg'], true)) {
            $extracted = self::extract_jpeg_carrier($carrier);
        } elseif ('image/png' === $mime) {
            $length = strlen($carrier) >= 12 ? unpack('N', substr($carrier, 0, 4))[1] : -1;
            $crc = strlen($carrier) >= 12 ? pack('H*', hash('crc32b', substr($carrier, 4, 4 + $length))) : '';
            $extracted = $length >= 0
                && strlen($carrier) === $length + 12
                && 'caBX' === substr($carrier, 4, 4)
                && hash_equals(substr($carrier, -4), $crc)
                ? substr($carrier, 8, $length)
                : new \WP_Error('carrier_structure_mismatch', 'The returned PNG carrier is malformed.');
        } elseif (in_array($mime, ['audio/wav', 'image/webp', 'video/x-msvideo'], true)) {
            $length = strlen($carrier) >= 8 ? unpack('V', substr($carrier, 4, 4))[1] : -1;
            $extracted = $length >= 0
                && 'C2PA' === substr($carrier, 0, 4)
                && strlen($carrier) === 8 + $length + ($length & 1)
                && (0 === ($length & 1) || "\0" === $carrier[strlen($carrier) - 1])
                ? substr($carrier, 8, $length)
                : new \WP_Error('carrier_structure_mismatch', 'The returned RIFF carrier is malformed.');
        } elseif ('image/gif' === $mime) {
            $extracted = self::extract_gif_carrier($carrier);
        } elseif ('image/svg+xml' === $mime) {
            $open = '<metadata><c2pa:manifest xmlns:c2pa="http://c2pa.org/manifest">';
            $close = '</c2pa:manifest></metadata>';
            if (! str_starts_with($carrier, $open) || ! str_ends_with($carrier, $close)) {
                $extracted = new \WP_Error('carrier_structure_mismatch', 'The returned SVG carrier is malformed.');
            } else {
                $encoded = substr($carrier, strlen($open), -strlen($close));
                $decoded = base64_decode($encoded, true);
                $extracted = false !== $decoded && base64_encode($decoded) === $encoded
                    ? $decoded
                    : new \WP_Error('carrier_structure_mismatch', 'The returned SVG manifest encoding is invalid.');
            }
        } elseif (in_array($mime, ['audio/mpeg', 'audio/flac'], true)) {
            $id3_prefix = is_resource($source) ? self::read_exact_at($source, 0, 4) : '';
            $tagged = is_string($id3_prefix) && str_starts_with($id3_prefix, 'ID3');
            $major = $tagged ? ord($id3_prefix[3]) : 3;
            $extracted = self::extract_id3_carrier($carrier, $tagged, $major);
        } elseif ('audio/ogg' === $mime) {
            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- php://temp is an in-memory stream.
            $handle = fopen('php://temp', 'w+b');
            // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fwrite -- php://temp is an in-memory stream.
            fwrite($handle, $carrier);
            $pages = self::parse_ogg_pages($handle, strlen($carrier), true);
            $extracted = is_wp_error($pages)
                ? new \WP_Error('carrier_structure_mismatch', 'The returned Ogg carrier is malformed.')
                : self::extract_strict_ogg_carrier($handle, $pages);
            fclose($handle);
        } elseif ('image/jxl' === $mime) {
            $length = strlen($carrier) >= 8 ? unpack('N', substr($carrier, 0, 4))[1] : -1;
            $extracted = 'jumb' === substr($carrier, 4, 4) && $length === strlen($carrier)
                ? $carrier
                : new \WP_Error('carrier_structure_mismatch', 'The returned JXL carrier is malformed.');
        } elseif (in_array($mime, ['image/tiff', 'image/x-adobe-dng'], true)) {
            $extracted = self::extract_tiff_carrier($carrier, $manifest, $plan, $source);
        } else {
            $extracted = self::extract_bmff_carrier($carrier);
        }
        if (is_wp_error($extracted) || ! hash_equals($manifest, $extracted)) {
            return is_wp_error($extracted)
                ? $extracted
                : new \WP_Error('carrier_manifest_mismatch', 'The returned carrier does not contain the returned manifest store.');
        }
        return true;
    }

    /** @return string|\WP_Error */
    private static function extract_jpeg_carrier(string $carrier)
    {
        $position = 0;
        $sequence = 1;
        $instance = null;
        $header = null;
        $payload = '';
        while ($position < strlen($carrier) && $sequence <= self::MAX_PLAN_ITEMS) {
            if ($position + 20 > strlen($carrier) || "\xff\xeb" !== substr($carrier, $position, 2)) {
                return new \WP_Error('carrier_structure_mismatch', 'The returned JPEG APP11 family is malformed.');
            }
            $length = unpack('n', substr($carrier, $position + 2, 2))[1];
            $end = $position + 2 + $length;
            if ($length < 18 || $end > strlen($carrier) || 'JP' !== substr($carrier, $position + 4, 2)) {
                return new \WP_Error('carrier_structure_mismatch', 'A returned JPEG APP11 segment is invalid.');
            }
            $en = unpack('n', substr($carrier, $position + 6, 2))[1];
            $z = unpack('N', substr($carrier, $position + 8, 4))[1];
            $lbox = unpack('N', substr($carrier, $position + 12, 4))[1];
            $header_length = 1 === $lbox ? 16 : 8;
            $packet_header = substr($carrier, $position + 12, $header_length);
            if (
                1 !== $en
                || $z !== $sequence
                || 'jumb' !== substr($packet_header, 4, 4)
                || (null !== $instance && $instance !== $en)
                || (null !== $header && $header !== $packet_header)
            ) {
                return new \WP_Error('carrier_structure_mismatch', 'The returned JPEG APP11 sequence is inconsistent.');
            }
            $instance = $en;
            $header = $packet_header;
            $payload .= substr($carrier, $position + 12 + $header_length, $end - ($position + 12 + $header_length));
            $position = $end;
            ++$sequence;
        }
        if (null === $header || $position !== strlen($carrier)) {
            return new \WP_Error('carrier_structure_mismatch', 'The returned JPEG APP11 carrier is incomplete.');
        }
        $store = $header . $payload;
        $declared = 1 === unpack('N', substr($header, 0, 4))[1]
            ? ((unpack('N', substr($header, 8, 4))[1] << 32) | unpack('N', substr($header, 12, 4))[1])
            : unpack('N', substr($header, 0, 4))[1];
        return $declared === strlen($store)
            ? $store
            : new \WP_Error('carrier_structure_mismatch', 'The returned JPEG manifest length is inconsistent.');
    }

    /** @return string|\WP_Error */
    private static function extract_gif_carrier(string $carrier)
    {
        if (! str_starts_with($carrier, "\x21\xff\x0b" . 'C2PA_GIF' . "\x01\x00\x00")) {
            return new \WP_Error('carrier_structure_mismatch', 'The returned GIF carrier header is invalid.');
        }
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- php://temp is an in-memory stream.
        $handle = fopen('php://temp', 'w+b');
        // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fwrite -- php://temp is an in-memory stream.
        fwrite($handle, $carrier);
        $end = self::gif_subblocks_end($handle, 14, strlen($carrier));
        $payload = is_wp_error($end) ? $end : self::collect_gif_subblocks($handle, 14, $end);
        fclose($handle);
        return ! is_wp_error($payload) && $end === strlen($carrier)
            ? $payload
            : new \WP_Error('carrier_structure_mismatch', 'The returned GIF sub-block carrier is malformed.');
    }

    /** @return string|\WP_Error */
    private static function extract_id3_carrier(string $carrier, bool $frame_only, int $major)
    {
        $frame_at = $frame_only ? 0 : 10;
        if (
            ! in_array($major, [3, 4], true)
            || strlen($carrier) < $frame_at + 10
            || 'GEOB' !== substr($carrier, $frame_at, 4)
            || "\0\0" !== substr($carrier, $frame_at + 8, 2)
        ) {
            return new \WP_Error('carrier_structure_mismatch', 'The returned ID3 carrier is malformed.');
        }
        if (! $frame_only) {
            if ('ID3' !== substr($carrier, 0, 3) || "\x03\0\0" !== substr($carrier, 3, 3)) {
                return new \WP_Error('carrier_structure_mismatch', 'The returned ID3 tag header is not canonical.');
            }
            $tag_size = 0;
            for ($index = 6; $index < 10; ++$index) {
                $byte = ord($carrier[$index]);
                if (0 !== ($byte & 0x80)) {
                    return new \WP_Error('carrier_structure_mismatch', 'The returned ID3 tag size is invalid.');
                }
                $tag_size = ($tag_size << 7) | $byte;
            }
            if (strlen($carrier) !== 10 + $tag_size) {
                return new \WP_Error('carrier_structure_mismatch', 'The returned ID3 tag geometry is inconsistent.');
            }
        }
        if (4 === $major && $frame_only) {
            $frame_size = 0;
            for ($index = $frame_at + 4; $index < $frame_at + 8; ++$index) {
                $byte = ord($carrier[$index]);
                if (0 !== ($byte & 0x80)) {
                    return new \WP_Error('carrier_structure_mismatch', 'The returned ID3 frame size is not synchsafe.');
                }
                $frame_size = ($frame_size << 7) | $byte;
            }
        } else {
            $frame_size = unpack('N', substr($carrier, $frame_at + 4, 4))[1];
        }
        if (strlen($carrier) !== $frame_at + 10 + $frame_size) {
            return new \WP_Error('carrier_structure_mismatch', 'The returned ID3 frame geometry is inconsistent.');
        }
        return self::extract_id3_geob_store(substr($carrier, $frame_at + 10, $frame_size));
    }

    /** @return string|\WP_Error */
    private static function extract_bmff_carrier(string $carrier)
    {
        if (strlen($carrier) < 53) {
            return new \WP_Error('carrier_structure_mismatch', 'The returned BMFF carrier is truncated.');
        }
        $size32 = unpack('N', substr($carrier, 0, 4))[1];
        $header = 1 === $size32 ? 16 : 8;
        $declared = 1 === $size32
            ? ((unpack('N', substr($carrier, 8, 4))[1] << 32) | unpack('N', substr($carrier, 12, 4))[1])
            : $size32;
        $prefix = hex2bin(self::C2PA_UUID_HEX) . "\0\0\0\0manifest\0" . str_repeat("\0", 8);
        return $declared === strlen($carrier)
            && 'uuid' === substr($carrier, 4, 4)
            && $prefix === substr($carrier, $header, strlen($prefix))
            ? substr($carrier, $header + strlen($prefix))
            : new \WP_Error('carrier_structure_mismatch', 'The returned BMFF UUID carrier is malformed.');
    }

    /** @return string|\WP_Error */
    private static function extract_tiff_carrier(string $carrier, string $manifest, array $plan, $source = null)
    {
        $insert = null;
        foreach ($plan['edits'] ?? [] as $edit) {
            if ('insert_carrier' === ($edit['op'] ?? null) && is_int($edit['offset'] ?? null)) {
                $insert = $edit['offset'];
                break;
            }
        }
        if (! is_int($insert)) {
            return new \WP_Error('carrier_structure_mismatch', 'The TIFF carrier insertion coordinate is missing.');
        }
        $manifest_at = $insert & 1 ? 1 : 0;
        $after = $manifest_at + strlen($manifest);
        $ifd_at = $after + (($insert + $after) & 1);
        if (
            $ifd_at + 18 > strlen($carrier)
            || (1 === $manifest_at && "\0" !== $carrier[0])
            || substr($carrier, $manifest_at, strlen($manifest)) !== $manifest
            || ($ifd_at > $after && "\0" !== $carrier[$after])
        ) {
            return new \WP_Error('carrier_structure_mismatch', 'The returned TIFF carrier payload geometry is invalid.');
        }
        $byte_orders = [true, false];
        if (is_resource($source)) {
            $header = self::read_exact_at($source, 0, 8);
            if (is_wp_error($header) || ! in_array(substr($header, 0, 2), ['II', 'MM'], true)) {
                return new \WP_Error('carrier_structure_mismatch', 'The local TIFF byte order is unavailable.');
            }
            $byte_orders = ['II' === substr($header, 0, 2)];
        }
        foreach ($byte_orders as $little) {
            $u16 = static fn(string $bytes): int => unpack($little ? 'v' : 'n', $bytes)[1];
            $u32 = static fn(string $bytes): int => unpack($little ? 'V' : 'N', $bytes)[1];
            $count = $u16(substr($carrier, $ifd_at, 2));
            $ifd_length = 2 + 12 * $count + 4;
            if ($count > self::MAX_PLAN_ITEMS || $ifd_at + $ifd_length !== strlen($carrier)) {
                continue;
            }
            $found = false;
            $last_tag = -1;
            $returned_entries = [];
            for ($index = 0; $index < $count; ++$index) {
                $entry = substr($carrier, $ifd_at + 2 + 12 * $index, 12);
                $tag = $u16(substr($entry, 0, 2));
                if ($tag < $last_tag) {
                    continue 2;
                }
                $last_tag = $tag;
                if (0xcd41 === $tag) {
                    $found = 7 === $u16(substr($entry, 2, 2))
                        && strlen($manifest) === $u32(substr($entry, 4, 4))
                        && $insert + $manifest_at === $u32(substr($entry, 8, 4));
                } else {
                    $returned_entries[] = $entry;
                }
            }
            if ($found) {
                if (is_resource($source)) {
                    $first_ifd = $u32(substr($header, 4, 4));
                    $local_count_bytes = self::read_exact_at($source, $first_ifd, 2);
                    if (is_wp_error($local_count_bytes)) {
                        return $local_count_bytes;
                    }
                    $local_count = $u16($local_count_bytes);
                    $local_table = self::read_exact_at($source, $first_ifd + 2, 12 * $local_count + 4);
                    if (is_wp_error($local_table)) {
                        return $local_table;
                    }
                    $expected_entries = [];
                    for ($index = 0; $index < $local_count; ++$index) {
                        $entry = substr($local_table, 12 * $index, 12);
                        if (0xcd41 !== $u16(substr($entry, 0, 2))) {
                            $expected_entries[] = $entry;
                        }
                    }
                    usort(
                        $expected_entries,
                        static fn(string $left, string $right): int => $u16(substr($left, 0, 2)) <=> $u16(substr($right, 0, 2))
                    );
                    if (
                        $returned_entries !== $expected_entries
                        || substr($carrier, $ifd_at + 2 + 12 * $count, 4) !== substr($local_table, 12 * $local_count, 4)
                    ) {
                        return new \WP_Error('carrier_structure_mismatch', 'The returned TIFF carrier changed local IFD entries.');
                    }
                }
                return $manifest;
            }
        }
        return new \WP_Error('carrier_structure_mismatch', 'The returned TIFF IFD carrier is malformed.');
    }

    /** @return true|\WP_Error */
    private static function validate_store_bytes(string $store, string $format)
    {
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- php://temp is an in-memory stream.
        $handle = fopen('php://temp', 'w+b');
        // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fwrite -- php://temp is an in-memory stream.
        if (false === $handle || strlen($store) !== fwrite($handle, $store)) {
            return new \WP_Error('media_read_failed', 'Could not inspect a manifest store.');
        }
        $result = HashMediaPlanner::validate_store_payload($handle, 0, strlen($store), $format);
        fclose($handle);
        return $result;
    }

    /**
     * @param array<int,array{0:int,1:int}> $deletes
     * @param array<int,array{0:int,1:string}> $patches
     * @return array{edits:array<int,array<string,mixed>>,final_size:int,output_start:int}
     */
    private static function canonical_data_geometry(
        int $source_size,
        int $insert_at,
        int $carrier_length,
        array $deletes,
        array $patches
    ): array {
        $operations = [];
        foreach ($deletes as [$offset, $length]) {
            $operations[] = [
                'offset' => $offset,
                'priority' => 1,
                'edit' => ['op' => 'delete', 'offset' => $offset, 'length' => $length],
            ];
        }
        foreach ($patches as [$offset, $bytes]) {
            $operations[] = [
                'offset' => $offset,
                'priority' => 2,
                'edit' => ['op' => 'patch', 'offset' => $offset, 'b64' => base64_encode($bytes)],
            ];
        }
        $operations[] = [
            'offset' => $insert_at,
            'priority' => 0,
            'edit' => ['op' => 'insert_carrier', 'offset' => $insert_at, 'length' => $carrier_length],
        ];
        usort(
            $operations,
            static fn(array $left, array $right): int => [$left['offset'], $left['priority']] <=> [$right['offset'], $right['priority']]
        );
        $removed = array_sum(array_column($deletes, 1));
        $removed_before = 0;
        foreach ($deletes as [$offset, $length]) {
            if ($offset < $insert_at && $offset + $length <= $insert_at) {
                $removed_before += $length;
            }
        }
        return [
            'edits' => array_column($operations, 'edit'),
            'final_size' => $source_size - $removed + $carrier_length,
            'output_start' => $insert_at - $removed_before,
        ];
    }

    /** @return array<int,array<string,mixed>>|\WP_Error */
    private static function derive_bmff_hash_program(
        $source,
        int $source_size,
        int $expected_size,
        array $edits,
        array $plan
    ) {
        if (($plan['exclusions'] ?? null) !== self::BMFF_EXCLUSIONS) {
            return new \WP_Error('plan_invalid', 'The BMFF signing plan does not use the canonical exclusions.');
        }
        $boxes = self::parse_bmff_top_boxes($source, $source_size);
        if (is_wp_error($boxes)) {
            return $boxes;
        }

        $local_carriers = array_values(array_filter(
            $boxes,
            static fn(array $box): bool => $box['c2pa']
        ));
        if (count($local_carriers) > 1) {
            return new \WP_Error('structure_invalid', 'Multiple C2PA BMFF carriers are ambiguous.');
        }

        $deletes = [];
        $patches = [];
        $insert = null;
        $prior_key = [-1, -1];
        foreach ($edits as $edit) {
            if (! is_array($edit) || ! is_string($edit['op'] ?? null)) {
                return new \WP_Error('plan_invalid', 'The BMFF signing edit list is malformed.');
            }
            $offset = self::strict_nonnegative_int($edit['offset'] ?? null);
            if ('insert_carrier' === $edit['op']) {
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                $priority = 0;
                if (null !== $insert) {
                    return new \WP_Error('plan_invalid', 'The BMFF signing plan contains multiple carrier insertions.');
                }
                $insert = [$offset, $length];
            } elseif ('delete' === $edit['op']) {
                $length = self::strict_nonnegative_int($edit['length'] ?? null);
                $priority = 1;
                $deletes[] = [$offset, $length];
            } elseif ('patch' === $edit['op']) {
                $bytes = base64_decode((string) ($edit['b64'] ?? ''), true);
                $length = false === $bytes ? null : strlen($bytes);
                $priority = 2;
                if (false === $bytes || '' === $bytes || base64_encode($bytes) !== ($edit['b64'] ?? null)) {
                    return new \WP_Error('plan_invalid', 'A BMFF signing patch is invalid.');
                }
                $patches[] = [$offset, $bytes];
            } else {
                return new \WP_Error('plan_invalid', 'The BMFF signing edit list contains an unknown operation.');
            }
            if (
                null === $offset
                || null === $length
                || $length <= 0
                || $offset > $source_size
                || $offset + $length < $offset
                || $offset + (0 === $priority ? 0 : $length) > $source_size
                || $offset < $prior_key[0]
                || ($offset === $prior_key[0] && $priority < $prior_key[1])
            ) {
                return new \WP_Error('plan_invalid', 'A BMFF signing edit operation is out of order or out of bounds.');
            }
            $prior_key = [$offset, $priority];
        }
        if (null === $insert || null === $insert[0] || null === $insert[1]) {
            return new \WP_Error('plan_invalid', 'The BMFF manifest carrier insertion is missing.');
        }

        $canonical_insert = (isset($boxes[0]) && 0 === $boxes[0]['start'] && 'ftyp' === $boxes[0]['type'])
            ? $boxes[0]['end']
            : 0;
        if (isset($local_carriers[0]) && $local_carriers[0]['start'] !== $canonical_insert) {
            return new \WP_Error('structure_invalid', 'The existing BMFF C2PA carrier is not at the canonical insertion point.');
        }
        $canonical_deletes = array_map(
            static fn(array $box): array => [$box['start'], $box['end'] - $box['start']],
            $local_carriers
        );
        if ($insert[0] !== $canonical_insert || $deletes !== $canonical_deletes) {
            return new \WP_Error('plan_geometry_mismatch', 'The BMFF carrier edit does not match the locally parsed box geometry.');
        }

        $last_delete_end = 0;
        foreach ($deletes as [$offset, $length]) {
            if ($offset < $last_delete_end) {
                return new \WP_Error('plan_invalid', 'BMFF delete ranges overlap.');
            }
            $last_delete_end = $offset + $length;
        }
        $removed = array_sum(array_column($deletes, 1));
        $canonical_patches = self::derive_bmff_offset_patches(
            $source,
            $source_size,
            $insert[1] - $removed
        );
        if (is_wp_error($canonical_patches)) {
            return $canonical_patches;
        }
        if ($patches !== $canonical_patches) {
            return new \WP_Error('plan_invalid', 'The BMFF signing patches do not match the locally derived offset-table edits.');
        }

        $final_size = $source_size - $removed + $insert[1];
        $carrier_output_start = self::bmff_output_offset($insert[0], $deletes, $insert[0], 0);
        if (
            $final_size !== $expected_size
            || ($plan['carrier_span'] ?? null) !== ['offset' => 0, 'length' => $insert[1]]
            || ($plan['carrier_output_span'] ?? null) !== ['offset' => $carrier_output_start, 'length' => $insert[1]]
        ) {
            return new \WP_Error('plan_geometry_mismatch', 'The BMFF signing edits do not describe the complete output geometry.');
        }

        $program = [];
        foreach ($boxes as $box) {
            if ($box['c2pa'] || in_array($box['type'], self::BMFF_EXCLUDED_TYPES, true)) {
                continue;
            }
            $output_start = self::bmff_output_offset($box['start'], $deletes, $insert[0], $insert[1]);
            $program[] = ['lit' => base64_encode(self::uint64_be($output_start))];
            self::append_bmff_transformed_span($program, $box['start'], $box['end'], $patches);
        }
        if ([] === $program) {
            return new \WP_Error('structure_invalid', 'The BMFF file has no boxes covered by the hard binding.');
        }
        return $program;
    }

    /** @return array<int,array{start:int,end:int,type:string,c2pa:bool}>|\WP_Error */
    private static function parse_bmff_top_boxes($handle, int $size, bool $validate_existing = true)
    {
        $boxes = [];
        $position = 0;
        while ($position + 8 <= $size) {
            $header = self::read_exact_at($handle, $position, 8);
            if (is_wp_error($header)) {
                return $header;
            }
            $size32 = unpack('Nsize', substr($header, 0, 4))['size'];
            $type = substr($header, 4, 4);
            $header_length = 8;
            if (1 === $size32) {
                $large = self::read_exact_at($handle, $position + 8, 8);
                if (is_wp_error($large)) {
                    return $large;
                }
                $parts = unpack('Nhigh/Nlow', $large);
                if ($parts['high'] > 0x7fffffff) {
                    return new \WP_Error('structure_invalid', 'A BMFF box is too large for this platform.');
                }
                $box_size = ($parts['high'] * 4294967296) + $parts['low'];
                $header_length = 16;
            } elseif (0 === $size32) {
                $box_size = $size - $position;
            } else {
                $box_size = $size32;
            }
            $end = $position + $box_size;
            if ($box_size < $header_length || $end <= $position || $end > $size) {
                return new \WP_Error('structure_invalid', 'A BMFF top-level box is out of bounds.');
            }
            $is_c2pa = false;
            if ('uuid' === $type && $position + $header_length + 16 <= $end) {
                $uuid = self::read_exact_at($handle, $position + $header_length, 16);
                if (is_wp_error($uuid)) {
                    return $uuid;
                }
                $is_c2pa = self::C2PA_UUID_HEX === bin2hex($uuid);
                if ($is_c2pa && $validate_existing) {
                    $valid = HashMediaPlanner::validate_bmff_uuid_box(
                        $handle,
                        $position + $header_length,
                        $end
                    );
                    if (is_wp_error($valid)) {
                        return $valid;
                    }
                }
            }
            $boxes[] = ['start' => $position, 'end' => $end, 'type' => $type, 'c2pa' => $is_c2pa];
            $position = $end;
        }
        if ([] === $boxes || $position !== $size) {
            return new \WP_Error('structure_invalid', 'The BMFF top-level box table has a coverage gap.');
        }
        return $boxes;
    }


    /** @return array<int,array{0:int,1:string}>|\WP_Error */
    private static function derive_bmff_offset_patches($source, int $source_size, int $delta)
    {
        if (0 === $delta) {
            return [];
        }
        $offset_boxes = HashMediaPlanner::bmff_offset_boxes($source, $source_size);
        if (is_wp_error($offset_boxes)) {
            return $offset_boxes;
        }
        $patches = [];
        $items = 0;
        foreach ($offset_boxes as $box) {
            $offset = self::strict_nonnegative_int($box['offset'] ?? null);
            $original = $box['bytes'] ?? null;
            if (null === $offset || ! is_string($original)) {
                return new \WP_Error('structure_invalid', 'A local BMFF offset table is malformed.');
            }
            $patched = self::patch_bmff_offset_box($original, $delta, $items);
            if (is_wp_error($patched)) {
                return $patched;
            }
            $position = 0;
            $length = strlen($original);
            while ($position < $length) {
                if ($patched[$position] === $original[$position]) {
                    ++$position;
                    continue;
                }
                $start = $position;
                while ($position < $length && $patched[$position] !== $original[$position]) {
                    ++$position;
                }
                $patches[] = [$offset + $start, substr($patched, $start, $position - $start)];
                if (count($patches) > self::MAX_BMFF_PATCH_RUNS) {
                    return new \WP_Error('structure_too_large', 'The local BMFF offset tables require too many signing patches.');
                }
            }
        }
        return $patches;
    }

    /** @return string|\WP_Error */
    private static function patch_bmff_offset_box(string $bytes, int $delta, int &$items)
    {
        $length = strlen($bytes);
        if ($length < 8) {
            return new \WP_Error('structure_invalid', 'A local BMFF offset table is truncated.');
        }
        $size32 = self::read_bmff_uint($bytes, 0, 4);
        $type = substr($bytes, 4, 4);
        $header_length = 8;
        if (1 === $size32) {
            $box_size = self::read_bmff_uint($bytes, 8, 8);
            $header_length = 16;
        } elseif (0 === $size32) {
            $box_size = $length;
        } else {
            $box_size = $size32;
        }
        if ($box_size !== $length || $header_length > $length) {
            return new \WP_Error('structure_invalid', 'A local BMFF offset table has invalid box geometry.');
        }

        $valid = match ($type) {
            'stco' => self::patch_bmff_chunk_offsets($bytes, $header_length, false, $delta, $items),
            'co64' => self::patch_bmff_chunk_offsets($bytes, $header_length, true, $delta, $items),
            'iloc' => self::patch_bmff_iloc($bytes, $header_length, $delta, $items),
            'tfhd' => self::patch_bmff_tfhd($bytes, $header_length, $delta, $items),
            default => false,
        };
        return true === $valid
            ? $bytes
            : new \WP_Error('structure_invalid', 'A local BMFF offset table is malformed.');
    }

    private static function patch_bmff_chunk_offsets(
        string &$bytes,
        int $payload_start,
        bool $wide,
        int $delta,
        int &$items
    ): bool {
        $count = self::read_bmff_uint($bytes, $payload_start + 4, 4);
        $entry_size = $wide ? 8 : 4;
        $position = $payload_start + 8;
        if (
            null === $count
            || $count > self::MAX_BMFF_PATCH_ITEMS - $items
            || $count > intdiv(max(0, strlen($bytes) - $position), $entry_size)
        ) {
            return false;
        }
        for ($index = 0; $index < $count; ++$index) {
            if (! self::adjust_bmff_integer($bytes, $position, $entry_size, $delta)) {
                return false;
            }
            $position += $entry_size;
            ++$items;
        }
        return true;
    }

    private static function patch_bmff_tfhd(
        string &$bytes,
        int $payload_start,
        int $delta,
        int &$items
    ): bool {
        if ($payload_start + 4 > strlen($bytes)) {
            return false;
        }
        $flags = (ord($bytes[$payload_start + 1]) << 16)
            | (ord($bytes[$payload_start + 2]) << 8)
            | ord($bytes[$payload_start + 3]);
        if (0 === ($flags & 1)) {
            return true;
        }
        if ($items >= self::MAX_BMFF_PATCH_ITEMS) {
            return false;
        }
        ++$items;
        return self::adjust_bmff_integer($bytes, $payload_start + 8, 8, $delta);
    }

    private static function patch_bmff_iloc(
        string &$bytes,
        int $payload_start,
        int $delta,
        int &$items
    ): bool {
        $limit = strlen($bytes);
        if ($payload_start + 6 > $limit) {
            return false;
        }
        $version = ord($bytes[$payload_start]);
        if ($version > 2) {
            return false;
        }
        $offset_size = ord($bytes[$payload_start + 4]) >> 4;
        $length_size = ord($bytes[$payload_start + 4]) & 0x0f;
        $base_offset_size = ord($bytes[$payload_start + 5]) >> 4;
        $index_size = ord($bytes[$payload_start + 5]) & 0x0f;
        foreach ([$offset_size, $length_size, $base_offset_size, $index_size] as $size) {
            if (! in_array($size, [0, 4, 8], true)) {
                return false;
            }
        }

        $position = $payload_start + 6;
        $count_size = $version < 2 ? 2 : 4;
        $item_count = self::read_bmff_uint($bytes, $position, $count_size);
        if (null === $item_count || ! self::advance_bmff_position($position, $count_size, $limit)) {
            return false;
        }
        for ($item = 0; $item < $item_count; ++$item) {
            if ($items >= self::MAX_BMFF_PATCH_ITEMS) {
                return false;
            }
            ++$items;
            if (! self::advance_bmff_position($position, $version < 2 ? 2 : 4, $limit)) {
                return false;
            }
            if ($version >= 1) {
                if ($position + 2 > $limit) {
                    return false;
                }
                $construction_method = ord($bytes[$position + 1]) & 0x0f;
                $position += 2;
            } else {
                $construction_method = 0;
            }
            if (! self::advance_bmff_position($position, 2, $limit)) {
                return false;
            }
            $base_offset_position = $position;
            $base_offset = self::read_bmff_uint($bytes, $position, $base_offset_size);
            if (null === $base_offset || ! self::advance_bmff_position($position, $base_offset_size, $limit)) {
                return false;
            }
            if (
                0 === $construction_method
                && 0 !== $base_offset
                && ! self::adjust_bmff_integer($bytes, $base_offset_position, $base_offset_size, $delta)
            ) {
                return false;
            }
            $extent_count = self::read_bmff_uint($bytes, $position, 2);
            if (null === $extent_count || ! self::advance_bmff_position($position, 2, $limit)) {
                return false;
            }
            for ($extent = 0; $extent < $extent_count; ++$extent) {
                if ($items >= self::MAX_BMFF_PATCH_ITEMS) {
                    return false;
                }
                ++$items;
                if (
                    (($version === 1 || $version === 2) && ! self::advance_bmff_position($position, $index_size, $limit))
                ) {
                    return false;
                }
                $extent_offset_position = $position;
                $extent_offset = self::read_bmff_uint($bytes, $position, $offset_size);
                if (null === $extent_offset || ! self::advance_bmff_position($position, $offset_size, $limit)) {
                    return false;
                }
                if (
                    0 === $construction_method
                    && 0 === $base_offset
                    && 0 !== $extent_offset
                    && ! self::adjust_bmff_integer($bytes, $extent_offset_position, $offset_size, $delta)
                ) {
                    return false;
                }
                if (! self::advance_bmff_position($position, $length_size, $limit)) {
                    return false;
                }
            }
        }
        return $position <= $limit;
    }

    private static function advance_bmff_position(int &$position, int $length, int $limit): bool
    {
        if ($length < 0 || $position < 0 || $position > $limit - $length) {
            return false;
        }
        $position += $length;
        return true;
    }

    private static function adjust_bmff_integer(string &$bytes, int $offset, int $width, int $delta): bool
    {
        if (! in_array($width, [4, 8], true)) {
            return false;
        }
        $current = self::read_bmff_uint($bytes, $offset, $width);
        if (
            null === $current
            || ($delta < 0 && $current < -$delta)
            || ($delta > 0 && $current > PHP_INT_MAX - $delta)
        ) {
            return false;
        }
        $adjusted = $current + $delta;
        if (4 === $width && $adjusted > 0xffffffff) {
            return false;
        }
        $replacement = 4 === $width ? pack('N', $adjusted) : self::uint64_be($adjusted);
        $bytes = substr_replace($bytes, $replacement, $offset, $width);
        return true;
    }

    private static function read_bmff_uint(string $bytes, int $offset, int $width): ?int
    {
        if ($offset < 0 || $width < 0 || $offset > strlen($bytes) - $width) {
            return null;
        }
        if (0 === $width) {
            return 0;
        }
        if (2 === $width) {
            return unpack('nvalue', substr($bytes, $offset, 2))['value'];
        }
        if (4 === $width) {
            return unpack('Nvalue', substr($bytes, $offset, 4))['value'];
        }
        if (8 !== $width) {
            return null;
        }
        $parts = unpack('Nhigh/Nlow', substr($bytes, $offset, 8));
        if ($parts['high'] > intdiv(PHP_INT_MAX - $parts['low'], 4294967296)) {
            return null;
        }
        return ($parts['high'] * 4294967296) + $parts['low'];
    }

    private static function bmff_output_offset(int $original, array $deletes, int $insert_at, int $inserted_length): int
    {
        $removed_before = 0;
        foreach ($deletes as [$start, $length]) {
            if ($start + $length <= $original && $start < $original) {
                $removed_before += $length;
            }
        }
        return $original - $removed_before + ($original >= $insert_at ? $inserted_length : 0);
    }

    private static function uint64_be(int $value): string
    {
        return pack('N2', intdiv($value, 4294967296), $value % 4294967296);
    }

    private static function append_bmff_transformed_span(
        array &$program,
        int $start,
        int $end,
        array $patches
    ): void {
        $cursor = $start;
        foreach ($patches as [$offset, $bytes]) {
            if ($offset < $start || $offset >= $end) {
                continue;
            }
            if ($cursor < $offset) {
                $program[] = ['range' => [$cursor, $offset - $cursor]];
            }
            $program[] = ['lit' => base64_encode($bytes)];
            $cursor = $offset + strlen($bytes);
        }
        if ($cursor < $end) {
            $program[] = ['range' => [$cursor, $end - $cursor]];
        }
    }

    /** @return string|\WP_Error */
    private static function read_exact_at($handle, int $offset, int $length)
    {
        if ($offset < 0 || $length <= 0 || 0 !== fseek($handle, $offset, SEEK_SET)) {
            return new \WP_Error('media_read_failed', 'Could not read the local BMFF structure.');
        }
        $bytes = '';
        while (strlen($bytes) < $length) {
            $part = fread($handle, $length - strlen($bytes)); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- Bounded exact reads from the locked seekable media stream have no WP_Filesystem equivalent.
            if (false === $part || '' === $part) {
                return new \WP_Error('media_read_failed', 'Could not read the local BMFF structure.');
            }
            $bytes .= $part;
        }
        return $bytes;
    }

    private static function strict_nonnegative_int($value): ?int
    {
        return is_int($value) && $value >= 0 ? $value : null;
    }

    private static function append_range_item(array &$program, int $offset, int $length): void
    {
        $last = count($program) - 1;
        if ($last >= 0 && isset($program[$last]['range'])) {
            [$prior_offset, $prior_length] = $program[$last]['range'];
            if ($prior_offset + $prior_length === $offset) {
                $program[$last]['range'][1] += $length;
                return;
            }
        }
        $program[] = ['range' => [$offset, $length]];
    }


    /** @return string|\WP_Error */
    private static function hash_program($handle, array $recipe, ?callable $heartbeat = null)
    {
        $context = hash_init('sha256');
        $size = (int) (fstat($handle)['size'] ?? -1);
        if ($size < 0 || [] === $recipe) {
            return new \WP_Error('plan_invalid', 'The signing hash recipe is missing.');
        }
        foreach ($recipe as $item) {
            if (isset($item['lit'])) {
                $literal = base64_decode((string) $item['lit'], true);
                if (false === $literal) {
                    return new \WP_Error('plan_invalid', 'A signing hash literal is not valid base64.');
                }
                hash_update($context, $literal);
                continue;
            }
            $range = $item['range'] ?? null;
            if (! is_array($range) || 2 !== count($range)) {
                return new \WP_Error('plan_invalid', 'The signing hash recipe is malformed.');
            }
            $offset = (int) $range[0];
            $length = (int) $range[1];
            if ($offset < 0 || $length < 0 || $offset + $length > $size || 0 !== fseek($handle, $offset, SEEK_SET)) {
                return new \WP_Error('plan_invalid', 'A signing hash range is out of bounds.');
            }
            while ($length > 0) {
                $lease = self::check_heartbeat($heartbeat);
                if (is_wp_error($lease)) {
                    return $lease;
                }
                $bytes = fread($handle, min(self::COPY_CHUNK, $length)); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- Execute bounded sparse ranges against the already locked local stream.
                if (false === $bytes || '' === $bytes) {
                    return new \WP_Error('media_read_failed', 'Could not execute the signing hash recipe.');
                }
                hash_update($context, $bytes);
                $length -= strlen($bytes);
            }
        }
        return hash_final($context);
    }

    /** @return true|\WP_Error */
    private static function copy_range($source, $output, int $offset, int $length, ?callable $heartbeat)
    {
        if (0 !== fseek($source, $offset, SEEK_SET)) {
            return new \WP_Error('media_read_failed', 'Could not seek within the source media file.');
        }
        while ($length > 0) {
            $lease = self::check_heartbeat($heartbeat);
            if (is_wp_error($lease)) {
                return $lease;
            }
            $bytes = fread($source, min(self::COPY_CHUNK, $length)); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- Stream a bounded range from the locked local source into the private splice output.
            if (false === $bytes || '' === $bytes) {
                return new \WP_Error('media_read_failed', 'Could not stream the source media file.');
            }
            $written = self::write_all($output, $bytes, $heartbeat);
            if (is_wp_error($written)) {
                return $written;
            }
            $length -= strlen($bytes);
        }
        return true;
    }

    /** @return true|\WP_Error */
    private static function write_all($handle, string $bytes, ?callable $heartbeat)
    {
        $offset = 0;
        $length = strlen($bytes);
        while ($offset < $length) {
            $lease = self::check_heartbeat($heartbeat);
            if (is_wp_error($lease)) {
                return $lease;
            }
            $written = fwrite($handle, substr($bytes, $offset, self::COPY_CHUNK)); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fwrite,WordPress.WP.AlternativeFunctions.file_system_operations_fwrite -- Exact signed bytes must be written to the seekable private splice stream.
            if (false === $written || 0 === $written) {
                return new \WP_Error('media_write_failed', 'Could not write the local signed media file.');
            }
            $offset += $written;
        }
        return true;
    }

    /** @return true|\WP_Error */
    private static function write_zeros($handle, int $length, ?callable $heartbeat)
    {
        $block = str_repeat("\0", min(self::COPY_CHUNK, max(1, $length)));
        while ($length > 0) {
            $part = min(strlen($block), $length);
            $written = self::write_all($handle, substr($block, 0, $part), $heartbeat);
            if (is_wp_error($written)) {
                return $written;
            }
            $length -= $part;
        }
        return true;
    }

    /** @return string|\WP_Error */
    private static function hash_assembled_output(
        $handle,
        array $plan,
        int $carrier_start,
        int $carrier_length,
        ?callable $heartbeat
    ) {
        if ('c2pa.hash.bmff.v3' !== ($plan['binding_algorithm'] ?? 'c2pa.hash.data')) {
            return self::hash_output_without_carrier($handle, $carrier_start, $carrier_length, $heartbeat);
        }
        $stat = fstat($handle);
        $size = is_array($stat) ? (int) ($stat['size'] ?? -1) : -1;
        $boxes = self::parse_bmff_top_boxes($handle, $size, false);
        if (is_wp_error($boxes)) {
            return $boxes;
        }
        $carriers = array_values(array_filter(
            $boxes,
            static fn(array $box): bool => $box['c2pa']
        ));
        if (
            1 !== count($carriers)
            || $carriers[0]['start'] !== $carrier_start
            || $carriers[0]['end'] - $carriers[0]['start'] !== $carrier_length
        ) {
            return new \WP_Error('carrier_geometry_mismatch', 'The assembled BMFF carrier is missing or ambiguous.');
        }
        $program = [];
        foreach ($boxes as $box) {
            if ($box['c2pa'] || in_array($box['type'], self::BMFF_EXCLUDED_TYPES, true)) {
                continue;
            }
            $program[] = ['lit' => base64_encode(self::uint64_be($box['start']))];
            $program[] = ['range' => [$box['start'], $box['end'] - $box['start']]];
        }
        return self::hash_program($handle, $program, $heartbeat);
    }

    /** @return string|\WP_Error */
    private static function hash_output_without_carrier($handle, int $carrier_start, int $carrier_length, ?callable $heartbeat)
    {
        $stat = fstat($handle);
        $size = is_array($stat) ? (int) ($stat['size'] ?? -1) : -1;
        if ($carrier_start < 0 || $carrier_length <= 0 || $carrier_start + $carrier_length > $size) {
            return new \WP_Error('carrier_geometry_mismatch', 'The signed carrier is outside the assembled file.');
        }
        $context = hash_init('sha256');
        foreach ([[0, $carrier_start], [$carrier_start + $carrier_length, $size - $carrier_start - $carrier_length]] as [$offset, $length]) {
            if (0 !== fseek($handle, $offset, SEEK_SET)) {
                return new \WP_Error('media_read_failed', 'Could not recheck the assembled hard binding.');
            }
            while ($length > 0) {
                $lease = self::check_heartbeat($heartbeat);
                if (is_wp_error($lease)) {
                    return $lease;
                }
                $bytes = fread($handle, min(self::COPY_CHUNK, $length)); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- Rehash bounded host spans on the seekable assembled-output stream.
                if (false === $bytes || '' === $bytes) {
                    return new \WP_Error('media_read_failed', 'Could not recheck the assembled hard binding.');
                }
                hash_update($context, $bytes);
                $length -= strlen($bytes);
            }
        }
        return hash_final($context);
    }

    /** @return string|\WP_Error */
    private static function hash_stream($handle, ?callable $heartbeat)
    {
        if (0 !== fseek($handle, 0, SEEK_SET)) {
            return new \WP_Error('media_read_failed', 'Could not hash the signed media file.');
        }
        $context = hash_init('sha256');
        while (! feof($handle)) {
            $lease = self::check_heartbeat($heartbeat);
            if (is_wp_error($lease)) {
                return $lease;
            }
            $bytes = fread($handle, self::COPY_CHUNK); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- Compute the final digest from the seekable private output stream before atomic replacement.
            if (false === $bytes) {
                return new \WP_Error('media_read_failed', 'Could not hash the signed media file.');
            }
            if ('' !== $bytes) {
                hash_update($context, $bytes);
            }
        }
        return hash_final($context);
    }

    /** @return true|\WP_Error */
    private static function check_heartbeat(?callable $heartbeat)
    {
        if (null !== $heartbeat && ! $heartbeat()) {
            return new \WP_Error('signing_lease_lost', 'The media signing lease could not be renewed.');
        }
        return true;
    }

    private static function same_identity(array $before, array $after): bool
    {
        foreach (['dev', 'ino'] as $field) {
            if (! array_key_exists($field, $before) || ! array_key_exists($field, $after) || $before[$field] !== $after[$field]) {
                return false;
            }
        }
        return true;
    }
}
