package androidx.media3.exoplayer.text;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcel;
import androidx.annotation.Nullable;
import androidx.media3.common.Format;
import androidx.media3.common.MimeTypes;
import androidx.media3.common.text.Cue;
import androidx.media3.common.text.CueGroup;
import androidx.media3.common.util.Assertions;
import androidx.media3.common.util.BundleCollectionUtil;
import androidx.media3.common.util.Log;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import androidx.media3.exoplayer.BaseRenderer;
import androidx.media3.exoplayer.FormatHolder;
import androidx.media3.exoplayer.RendererCapabilities;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.extractor.text.SubtitleDecoderException;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Objects;
import n2.b;
import n2.g;
import n2.h;
import n2.k;
import n2.l;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
import org.checkerframework.dataflow.qual.SideEffectFree;
import s1.f;

/* JADX INFO: loaded from: classes.dex */
@UnstableApi
public final class TextRenderer extends BaseRenderer implements Handler.Callback {
    private static final int MSG_UPDATE_OUTPUT = 1;
    private static final int REPLACEMENT_STATE_NONE = 0;
    private static final int REPLACEMENT_STATE_SIGNAL_END_OF_STREAM = 1;
    private static final int REPLACEMENT_STATE_WAIT_END_OF_STREAM = 2;
    private static final String TAG = "TextRenderer";
    private final n2.a cueDecoder;
    private final f cueDecoderInputBuffer;
    private CuesResolver cuesResolver;
    private int decoderReplacementState;
    private long finalStreamEndPositionUs;
    private final FormatHolder formatHolder;
    private boolean inputStreamEnded;
    private long lastRendererPositionUs;
    private boolean legacyDecodingEnabled;

    @Nullable
    private l nextSubtitle;
    private int nextSubtitleEventIndex;

    @Nullable
    private k nextSubtitleInputBuffer;
    private final TextOutput output;

    @Nullable
    private final Handler outputHandler;
    private boolean outputStreamEnded;

    @Nullable
    private Format streamFormat;

    @Nullable
    private l subtitle;

    @Nullable
    private h subtitleDecoder;
    private final SubtitleDecoderFactory subtitleDecoderFactory;
    private boolean waitingForKeyFrame;

    public TextRenderer(TextOutput textOutput, @Nullable Looper looper) {
        this(textOutput, looper, SubtitleDecoderFactory.DEFAULT);
    }

    @RequiresNonNull({"streamFormat"})
    private void assertLegacyDecodingEnabledIfRequired() {
        Assertions.checkState(this.legacyDecodingEnabled || Objects.equals(this.streamFormat.sampleMimeType, MimeTypes.APPLICATION_CEA608) || Objects.equals(this.streamFormat.sampleMimeType, MimeTypes.APPLICATION_MP4CEA608) || Objects.equals(this.streamFormat.sampleMimeType, MimeTypes.APPLICATION_CEA708), "Legacy decoding is disabled, can't handle " + this.streamFormat.sampleMimeType + " samples (expected application/x-media3-cues).");
    }

    private void clearOutput() {
        updateOutput(new CueGroup(ImmutableList.t(), getPresentationTimeUs(this.lastRendererPositionUs)));
    }

    @RequiresNonNull({"subtitle"})
    @SideEffectFree
    private long getCurrentEventTimeUs(long j10) {
        int iA = this.subtitle.a(j10);
        if (iA == 0 || this.subtitle.d() == 0) {
            return this.subtitle.timeUs;
        }
        if (iA != -1) {
            return this.subtitle.b(iA - 1);
        }
        return this.subtitle.b(r2.d() - 1);
    }

    private long getNextEventTime() {
        if (this.nextSubtitleEventIndex == -1) {
            return Long.MAX_VALUE;
        }
        Assertions.checkNotNull(this.subtitle);
        if (this.nextSubtitleEventIndex >= this.subtitle.d()) {
            return Long.MAX_VALUE;
        }
        return this.subtitle.b(this.nextSubtitleEventIndex);
    }

    @SideEffectFree
    private long getPresentationTimeUs(long j10) {
        Assertions.checkState(j10 != -9223372036854775807L);
        return j10 - getStreamOffsetUs();
    }

    private void handleDecoderError(SubtitleDecoderException subtitleDecoderException) {
        Log.e(TAG, "Subtitle decoding failed. streamFormat=" + this.streamFormat, subtitleDecoderException);
        clearOutput();
        replaceSubtitleDecoder();
    }

    private static boolean hasEventsAfter(@Nullable g gVar, long j10) {
        return gVar != null && gVar.d() > 0 && gVar.b(gVar.d() - 1) > j10;
    }

    private void initSubtitleDecoder() {
        this.waitingForKeyFrame = true;
        h hVarCreateDecoder = this.subtitleDecoderFactory.createDecoder((Format) Assertions.checkNotNull(this.streamFormat));
        this.subtitleDecoder = hVarCreateDecoder;
        hVarCreateDecoder.setOutputStartTimeUs(getLastResetPositionUs());
    }

    private void invokeUpdateOutputInternal(CueGroup cueGroup) {
        this.output.onCues(cueGroup.cues);
        this.output.onCues(cueGroup);
    }

    @SideEffectFree
    private static boolean isCuesWithTiming(Format format) {
        return Objects.equals(format.sampleMimeType, MimeTypes.APPLICATION_MEDIA3_CUES);
    }

    @RequiresNonNull({"this.cuesResolver"})
    private boolean readAndDecodeCuesWithTiming(long j10) {
        if (this.inputStreamEnded || readSource(this.formatHolder, this.cueDecoderInputBuffer, 0) != -4) {
            return false;
        }
        if (this.cueDecoderInputBuffer.isEndOfStream()) {
            this.inputStreamEnded = true;
            return false;
        }
        this.cueDecoderInputBuffer.flip();
        ByteBuffer byteBuffer = (ByteBuffer) Assertions.checkNotNull(this.cueDecoderInputBuffer.data);
        n2.a aVar = this.cueDecoder;
        long j11 = this.cueDecoderInputBuffer.timeUs;
        byte[] bArrArray = byteBuffer.array();
        int iArrayOffset = byteBuffer.arrayOffset();
        int iLimit = byteBuffer.limit();
        aVar.getClass();
        Parcel parcelObtain = Parcel.obtain();
        parcelObtain.unmarshall(bArrArray, iArrayOffset, iLimit);
        parcelObtain.setDataPosition(0);
        Bundle bundle = parcelObtain.readBundle(Bundle.class.getClassLoader());
        parcelObtain.recycle();
        b bVar = new b(BundleCollectionUtil.fromBundleList(new androidx.media3.common.b(19), (ArrayList) Assertions.checkNotNull(bundle.getParcelableArrayList("c"))), j11, bundle.getLong("d"));
        this.cueDecoderInputBuffer.clear();
        return this.cuesResolver.addCues(bVar, j10);
    }

    private void releaseSubtitleBuffers() {
        this.nextSubtitleInputBuffer = null;
        this.nextSubtitleEventIndex = -1;
        l lVar = this.subtitle;
        if (lVar != null) {
            lVar.release();
            this.subtitle = null;
        }
        l lVar2 = this.nextSubtitle;
        if (lVar2 != null) {
            lVar2.release();
            this.nextSubtitle = null;
        }
    }

    private void releaseSubtitleDecoder() {
        releaseSubtitleBuffers();
        ((h) Assertions.checkNotNull(this.subtitleDecoder)).release();
        this.subtitleDecoder = null;
        this.decoderReplacementState = 0;
    }

    @RequiresNonNull({"this.cuesResolver"})
    private void renderFromCuesWithTiming(long j10) {
        boolean andDecodeCuesWithTiming = readAndDecodeCuesWithTiming(j10);
        long nextCueChangeTimeUs = this.cuesResolver.getNextCueChangeTimeUs(this.lastRendererPositionUs);
        if (nextCueChangeTimeUs == Long.MIN_VALUE && this.inputStreamEnded && !andDecodeCuesWithTiming) {
            this.outputStreamEnded = true;
        }
        if ((nextCueChangeTimeUs != Long.MIN_VALUE && nextCueChangeTimeUs <= j10) || andDecodeCuesWithTiming) {
            ImmutableList<Cue> cuesAtTimeUs = this.cuesResolver.getCuesAtTimeUs(j10);
            long previousCueChangeTimeUs = this.cuesResolver.getPreviousCueChangeTimeUs(j10);
            updateOutput(new CueGroup(cuesAtTimeUs, getPresentationTimeUs(previousCueChangeTimeUs)));
            this.cuesResolver.discardCuesBeforeTimeUs(previousCueChangeTimeUs);
        }
        this.lastRendererPositionUs = j10;
    }

    /* JADX WARN: Removed duplicated region for block: B:38:0x008c  */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    private void renderFromSubtitles(long j10) {
        boolean z10;
        this.lastRendererPositionUs = j10;
        if (this.nextSubtitle == null) {
            ((h) Assertions.checkNotNull(this.subtitleDecoder)).setPositionUs(j10);
            try {
                this.nextSubtitle = (l) ((h) Assertions.checkNotNull(this.subtitleDecoder)).dequeueOutputBuffer();
            } catch (SubtitleDecoderException e10) {
                handleDecoderError(e10);
                return;
            }
        }
        if (getState() != 2) {
            return;
        }
        if (this.subtitle != null) {
            long nextEventTime = getNextEventTime();
            z10 = false;
            while (nextEventTime <= j10) {
                this.nextSubtitleEventIndex++;
                nextEventTime = getNextEventTime();
                z10 = true;
            }
        } else {
            z10 = false;
        }
        l lVar = this.nextSubtitle;
        if (lVar != null) {
            if (!lVar.isEndOfStream()) {
                if (lVar.timeUs <= j10) {
                    l lVar2 = this.subtitle;
                    if (lVar2 != null) {
                        lVar2.release();
                    }
                    this.nextSubtitleEventIndex = lVar.a(j10);
                    this.subtitle = lVar;
                    this.nextSubtitle = null;
                }
                Assertions.checkNotNull(this.subtitle);
                updateOutput(new CueGroup(this.subtitle.c(j10), getPresentationTimeUs(getCurrentEventTimeUs(j10))));
            } else if (!z10 && getNextEventTime() == Long.MAX_VALUE) {
                if (this.decoderReplacementState == 2) {
                    replaceSubtitleDecoder();
                } else {
                    releaseSubtitleBuffers();
                    this.outputStreamEnded = true;
                }
            }
            if (z10) {
            }
        } else if (z10) {
            Assertions.checkNotNull(this.subtitle);
            updateOutput(new CueGroup(this.subtitle.c(j10), getPresentationTimeUs(getCurrentEventTimeUs(j10))));
        }
        if (this.decoderReplacementState == 2) {
            return;
        }
        while (!this.inputStreamEnded) {
            try {
                k kVar = this.nextSubtitleInputBuffer;
                if (kVar == null) {
                    kVar = (k) ((h) Assertions.checkNotNull(this.subtitleDecoder)).dequeueInputBuffer();
                    if (kVar == null) {
                        return;
                    } else {
                        this.nextSubtitleInputBuffer = kVar;
                    }
                }
                if (this.decoderReplacementState == 1) {
                    kVar.setFlags(4);
                    ((h) Assertions.checkNotNull(this.subtitleDecoder)).queueInputBuffer(kVar);
                    this.nextSubtitleInputBuffer = null;
                    this.decoderReplacementState = 2;
                    return;
                }
                int source = readSource(this.formatHolder, kVar, 0);
                if (source == -4) {
                    if (kVar.isEndOfStream()) {
                        this.inputStreamEnded = true;
                        this.waitingForKeyFrame = false;
                    } else {
                        Format format = this.formatHolder.format;
                        if (format == null) {
                            return;
                        }
                        kVar.f30779a = format.subsampleOffsetUs;
                        kVar.flip();
                        this.waitingForKeyFrame &= !kVar.isKeyFrame();
                    }
                    if (!this.waitingForKeyFrame) {
                        ((h) Assertions.checkNotNull(this.subtitleDecoder)).queueInputBuffer(kVar);
                        this.nextSubtitleInputBuffer = null;
                    }
                } else if (source == -3) {
                    return;
                }
            } catch (SubtitleDecoderException e11) {
                handleDecoderError(e11);
                return;
            }
        }
    }

    private void replaceSubtitleDecoder() {
        releaseSubtitleDecoder();
        initSubtitleDecoder();
    }

    private void updateOutput(CueGroup cueGroup) {
        Handler handler = this.outputHandler;
        if (handler != null) {
            handler.obtainMessage(1, cueGroup).sendToTarget();
        } else {
            invokeUpdateOutputInternal(cueGroup);
        }
    }

    @Deprecated
    public void experimentalSetLegacyDecodingEnabled(boolean z10) {
        this.legacyDecodingEnabled = z10;
    }

    @Override // androidx.media3.exoplayer.Renderer
    public String getName() {
        return TAG;
    }

    @Override // android.os.Handler.Callback
    public boolean handleMessage(Message message) {
        if (message.what != 1) {
            throw new IllegalStateException();
        }
        invokeUpdateOutputInternal((CueGroup) message.obj);
        return true;
    }

    @Override // androidx.media3.exoplayer.Renderer
    public boolean isEnded() {
        return this.outputStreamEnded;
    }

    @Override // androidx.media3.exoplayer.Renderer
    public boolean isReady() {
        Format format = this.streamFormat;
        if (format == null) {
            return true;
        }
        if (!isCuesWithTiming((Format) Assertions.checkNotNull(format))) {
            return !this.outputStreamEnded && (!this.inputStreamEnded || hasEventsAfter(this.subtitle, this.lastRendererPositionUs) || hasEventsAfter(this.nextSubtitle, this.lastRendererPositionUs) || this.nextSubtitleInputBuffer == null);
        }
        if (((CuesResolver) Assertions.checkNotNull(this.cuesResolver)).getNextCueChangeTimeUs(this.lastRendererPositionUs) != Long.MIN_VALUE) {
            return true;
        }
        try {
            maybeThrowStreamError();
            return true;
        } catch (IOException unused) {
            return false;
        }
    }

    @Override // androidx.media3.exoplayer.BaseRenderer
    public void onDisabled() {
        this.streamFormat = null;
        this.finalStreamEndPositionUs = -9223372036854775807L;
        clearOutput();
        this.lastRendererPositionUs = -9223372036854775807L;
        if (this.subtitleDecoder != null) {
            releaseSubtitleDecoder();
        }
    }

    @Override // androidx.media3.exoplayer.BaseRenderer
    public void onPositionReset(long j10, boolean z10) {
        this.lastRendererPositionUs = j10;
        CuesResolver cuesResolver = this.cuesResolver;
        if (cuesResolver != null) {
            cuesResolver.clear();
        }
        clearOutput();
        this.inputStreamEnded = false;
        this.outputStreamEnded = false;
        this.finalStreamEndPositionUs = -9223372036854775807L;
        Format format = this.streamFormat;
        if (format == null || isCuesWithTiming(format)) {
            return;
        }
        if (this.decoderReplacementState != 0) {
            replaceSubtitleDecoder();
            return;
        }
        releaseSubtitleBuffers();
        h hVar = (h) Assertions.checkNotNull(this.subtitleDecoder);
        hVar.flush();
        hVar.setOutputStartTimeUs(getLastResetPositionUs());
    }

    @Override // androidx.media3.exoplayer.BaseRenderer
    public void onStreamChanged(Format[] formatArr, long j10, long j11, MediaSource.MediaPeriodId mediaPeriodId) {
        Format format = formatArr[0];
        this.streamFormat = format;
        if (isCuesWithTiming(format)) {
            this.cuesResolver = this.streamFormat.cueReplacementBehavior == 1 ? new MergingCuesResolver() : new ReplacingCuesResolver();
            return;
        }
        assertLegacyDecodingEnabledIfRequired();
        if (this.subtitleDecoder != null) {
            this.decoderReplacementState = 1;
        } else {
            initSubtitleDecoder();
        }
    }

    @Override // androidx.media3.exoplayer.Renderer
    public void render(long j10, long j11) {
        if (isCurrentStreamFinal()) {
            long j12 = this.finalStreamEndPositionUs;
            if (j12 != -9223372036854775807L && j10 >= j12) {
                releaseSubtitleBuffers();
                this.outputStreamEnded = true;
            }
        }
        if (this.outputStreamEnded) {
            return;
        }
        if (isCuesWithTiming((Format) Assertions.checkNotNull(this.streamFormat))) {
            Assertions.checkNotNull(this.cuesResolver);
            renderFromCuesWithTiming(j10);
        } else {
            assertLegacyDecodingEnabledIfRequired();
            renderFromSubtitles(j10);
        }
    }

    public void setFinalStreamEndPositionUs(long j10) {
        Assertions.checkState(isCurrentStreamFinal());
        this.finalStreamEndPositionUs = j10;
    }

    @Override // androidx.media3.exoplayer.RendererCapabilities
    public int supportsFormat(Format format) {
        if (isCuesWithTiming(format) || this.subtitleDecoderFactory.supportsFormat(format)) {
            return RendererCapabilities.create(format.cryptoType == 0 ? 4 : 2);
        }
        return MimeTypes.isText(format.sampleMimeType) ? RendererCapabilities.create(1) : RendererCapabilities.create(0);
    }

    public TextRenderer(TextOutput textOutput, @Nullable Looper looper, SubtitleDecoderFactory subtitleDecoderFactory) {
        super(3);
        this.output = (TextOutput) Assertions.checkNotNull(textOutput);
        this.outputHandler = looper == null ? null : Util.createHandler(looper, this);
        this.subtitleDecoderFactory = subtitleDecoderFactory;
        this.cueDecoder = new n2.a();
        this.cueDecoderInputBuffer = new f(1);
        this.formatHolder = new FormatHolder();
        this.finalStreamEndPositionUs = -9223372036854775807L;
        this.lastRendererPositionUs = -9223372036854775807L;
        this.legacyDecodingEnabled = false;
    }
}
