package androidx.media3.extractor.mkv;

import androidx.media3.common.util.ParsableByteArray;
import androidx.media3.extractor.ExtractorInput;

/* JADX INFO: loaded from: classes.dex */
final class Sniffer {
    private static final int ID_EBML = 440786851;
    private static final int SEARCH_LENGTH = 1024;
    private int peekLength;
    private final ParsableByteArray scratch = new ParsableByteArray(8);

    private long readUint(ExtractorInput extractorInput) {
        int i6 = 0;
        extractorInput.peekFully(this.scratch.getData(), 0, 1);
        int i7 = this.scratch.getData()[0] & 255;
        if (i7 == 0) {
            return Long.MIN_VALUE;
        }
        int i8 = 128;
        int i9 = 0;
        while ((i7 & i8) == 0) {
            i8 >>= 1;
            i9++;
        }
        int i10 = i7 & (~i8);
        extractorInput.peekFully(this.scratch.getData(), 1, i9);
        while (i6 < i9) {
            i6++;
            i10 = (this.scratch.getData()[i6] & 255) + (i10 << 8);
        }
        this.peekLength = i9 + 1 + this.peekLength;
        return i10;
    }

    public boolean sniff(ExtractorInput extractorInput) {
        long length = extractorInput.getLength();
        long j4 = 1024;
        if (length != -1 && length <= 1024) {
            j4 = length;
        }
        int i6 = (int) j4;
        extractorInput.peekFully(this.scratch.getData(), 0, 4);
        long unsignedInt = this.scratch.readUnsignedInt();
        this.peekLength = 4;
        while (unsignedInt != 440786851) {
            int i7 = this.peekLength + 1;
            this.peekLength = i7;
            if (i7 == i6) {
                return false;
            }
            extractorInput.peekFully(this.scratch.getData(), 0, 1);
            unsignedInt = ((unsignedInt << 8) & (-256)) | ((long) (this.scratch.getData()[0] & 255));
        }
        long uint = readUint(extractorInput);
        long j6 = this.peekLength;
        if (uint != Long.MIN_VALUE && (length == -1 || j6 + uint < length)) {
            while (true) {
                int i8 = this.peekLength;
                long j7 = j6 + uint;
                if (i8 < j7) {
                    if (readUint(extractorInput) == Long.MIN_VALUE) {
                        return false;
                    }
                    long uint2 = readUint(extractorInput);
                    if (uint2 < 0 || uint2 > 2147483647L) {
                        break;
                    }
                    if (uint2 != 0) {
                        int i9 = (int) uint2;
                        extractorInput.advancePeekPosition(i9);
                        this.peekLength += i9;
                    }
                } else if (i8 == j7) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }
}
