package io.netty.handler.codec.http2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import java.util.TreeMap;

/* JADX INFO: loaded from: classes.dex */
public class StreamBufferingEncoder extends DecoratingHttp2ConnectionEncoder {
    private boolean closed;
    private int maxConcurrentStreams;
    private final TreeMap<Integer, PendingStream> pendingStreams;

    public final class DataFrame extends Frame {
        public final ByteBuf data;
        public final boolean endOfStream;
        public final int padding;

        public DataFrame(ByteBuf byteBuf, int i2, boolean z2, ChannelPromise channelPromise) {
            super(channelPromise);
            this.data = byteBuf;
            this.padding = i2;
            this.endOfStream = z2;
        }

        @Override // io.netty.handler.codec.http2.StreamBufferingEncoder.Frame
        public void release(Throwable th) {
            super.release(th);
            ReferenceCountUtil.safeRelease(this.data);
        }

        @Override // io.netty.handler.codec.http2.StreamBufferingEncoder.Frame
        public void send(ChannelHandlerContext channelHandlerContext, int i2) {
            StreamBufferingEncoder.this.writeData(channelHandlerContext, i2, this.data, this.padding, this.endOfStream, this.promise);
        }
    }

    public static abstract class Frame {
        public final ChannelPromise promise;

        public Frame(ChannelPromise channelPromise) {
            this.promise = channelPromise;
        }

        public void release(Throwable th) {
            if (th == null) {
                this.promise.setSuccess();
            } else {
                this.promise.setFailure(th);
            }
        }

        public abstract void send(ChannelHandlerContext channelHandlerContext, int i2);
    }

    public final class HeadersFrame extends Frame {
        public final boolean endOfStream;
        public final boolean exclusive;
        public final Http2Headers headers;
        public final int padding;
        public final int streamDependency;
        public final short weight;

        public HeadersFrame(Http2Headers http2Headers, int i2, short s2, boolean z2, int i3, boolean z3, ChannelPromise channelPromise) {
            super(channelPromise);
            this.headers = http2Headers;
            this.streamDependency = i2;
            this.weight = s2;
            this.exclusive = z2;
            this.padding = i3;
            this.endOfStream = z3;
        }

        @Override // io.netty.handler.codec.http2.StreamBufferingEncoder.Frame
        public void send(ChannelHandlerContext channelHandlerContext, int i2) {
            StreamBufferingEncoder.this.writeHeaders(channelHandlerContext, i2, this.headers, this.streamDependency, this.weight, this.exclusive, this.padding, this.endOfStream, this.promise);
        }
    }

    public static final class Http2ChannelClosedException extends Http2Exception {
        private static final long serialVersionUID = 4768543442094476971L;

        public Http2ChannelClosedException() {
            super(Http2Error.REFUSED_STREAM, "Connection closed");
        }
    }

    public static final class Http2GoAwayException extends Http2Exception {
        private static final long serialVersionUID = 1326785622777291198L;
        private final byte[] debugData;
        private final long errorCode;
        private final int lastStreamId;

        public Http2GoAwayException(int i2, long j2, byte[] bArr) {
            super(Http2Error.STREAM_CLOSED);
            this.lastStreamId = i2;
            this.errorCode = j2;
            this.debugData = bArr;
        }

        public byte[] debugData() {
            return this.debugData;
        }

        public long errorCode() {
            return this.errorCode;
        }

        public int lastStreamId() {
            return this.lastStreamId;
        }
    }

    public static final class PendingStream {
        public final ChannelHandlerContext ctx;
        public final Queue<Frame> frames = new ArrayDeque(2);
        public final int streamId;

        public PendingStream(ChannelHandlerContext channelHandlerContext, int i2) {
            this.ctx = channelHandlerContext;
            this.streamId = i2;
        }

        public void close(Throwable th) {
            Iterator<Frame> it = this.frames.iterator();
            while (it.hasNext()) {
                it.next().release(th);
            }
        }

        public void sendFrames() {
            Iterator<Frame> it = this.frames.iterator();
            while (it.hasNext()) {
                it.next().send(this.ctx, this.streamId);
            }
        }
    }

    public StreamBufferingEncoder(Http2ConnectionEncoder http2ConnectionEncoder) {
        this(http2ConnectionEncoder, 100);
    }

    public StreamBufferingEncoder(Http2ConnectionEncoder http2ConnectionEncoder, int i2) {
        super(http2ConnectionEncoder);
        this.pendingStreams = new TreeMap<>();
        this.maxConcurrentStreams = i2;
        connection().addListener(new Http2ConnectionAdapter() { // from class: io.netty.handler.codec.http2.StreamBufferingEncoder.1
            @Override // io.netty.handler.codec.http2.Http2ConnectionAdapter, io.netty.handler.codec.http2.Http2Connection.Listener
            public void onGoAwayReceived(int i3, long j2, ByteBuf byteBuf) {
                StreamBufferingEncoder.this.cancelGoAwayStreams(i3, j2, byteBuf);
            }

            @Override // io.netty.handler.codec.http2.Http2ConnectionAdapter, io.netty.handler.codec.http2.Http2Connection.Listener
            public void onStreamClosed(Http2Stream http2Stream) {
                StreamBufferingEncoder.this.tryCreatePendingStreams();
            }
        });
    }

    private boolean canCreateStream() {
        return connection().local().numActiveStreams() < this.maxConcurrentStreams;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void cancelGoAwayStreams(int i2, long j2, ByteBuf byteBuf) {
        Iterator<PendingStream> it = this.pendingStreams.values().iterator();
        Http2GoAwayException http2GoAwayException = new Http2GoAwayException(i2, j2, ByteBufUtil.getBytes(byteBuf));
        while (it.hasNext()) {
            PendingStream next = it.next();
            if (next.streamId > i2) {
                it.remove();
                next.close(http2GoAwayException);
            }
        }
    }

    private boolean isExistingStream(int i2) {
        return i2 <= connection().local().lastStreamCreated();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void tryCreatePendingStreams() {
        while (!this.pendingStreams.isEmpty() && canCreateStream()) {
            PendingStream value = this.pendingStreams.pollFirstEntry().getValue();
            try {
                value.sendFrames();
            } catch (Throwable th) {
                value.close(th);
            }
        }
    }

    @Override // io.netty.handler.codec.http2.DecoratingHttp2FrameWriter, io.netty.handler.codec.http2.Http2FrameWriter, java.io.Closeable, java.lang.AutoCloseable
    public void close() {
        try {
            if (!this.closed) {
                this.closed = true;
                Http2ChannelClosedException http2ChannelClosedException = new Http2ChannelClosedException();
                while (!this.pendingStreams.isEmpty()) {
                    this.pendingStreams.pollFirstEntry().getValue().close(http2ChannelClosedException);
                }
            }
        } finally {
            super.close();
        }
    }

    public int numBufferedStreams() {
        return this.pendingStreams.size();
    }

    @Override // io.netty.handler.codec.http2.DecoratingHttp2ConnectionEncoder, io.netty.handler.codec.http2.Http2ConnectionEncoder
    public void remoteSettings(Http2Settings http2Settings) {
        super.remoteSettings(http2Settings);
        this.maxConcurrentStreams = connection().local().maxActiveStreams();
        tryCreatePendingStreams();
    }

    @Override // io.netty.handler.codec.http2.DecoratingHttp2FrameWriter, io.netty.handler.codec.http2.Http2DataWriter
    public ChannelFuture writeData(ChannelHandlerContext channelHandlerContext, int i2, ByteBuf byteBuf, int i3, boolean z2, ChannelPromise channelPromise) {
        if (isExistingStream(i2)) {
            return super.writeData(channelHandlerContext, i2, byteBuf, i3, z2, channelPromise);
        }
        PendingStream pendingStream = this.pendingStreams.get(Integer.valueOf(i2));
        if (pendingStream != null) {
            pendingStream.frames.add(new DataFrame(byteBuf, i3, z2, channelPromise));
        } else {
            ReferenceCountUtil.safeRelease(byteBuf);
            channelPromise.setFailure((Throwable) Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Stream does not exist %d", Integer.valueOf(i2)));
        }
        return channelPromise;
    }

    @Override // io.netty.handler.codec.http2.DecoratingHttp2FrameWriter, io.netty.handler.codec.http2.Http2FrameWriter
    public ChannelFuture writeHeaders(ChannelHandlerContext channelHandlerContext, int i2, Http2Headers http2Headers, int i3, short s2, boolean z2, int i4, boolean z3, ChannelPromise channelPromise) {
        if (this.closed) {
            return channelPromise.setFailure((Throwable) new Http2ChannelClosedException());
        }
        if (isExistingStream(i2) || connection().goAwayReceived()) {
            return super.writeHeaders(channelHandlerContext, i2, http2Headers, i3, s2, z2, i4, z3, channelPromise);
        }
        if (canCreateStream()) {
            return super.writeHeaders(channelHandlerContext, i2, http2Headers, i3, s2, z2, i4, z3, channelPromise);
        }
        PendingStream pendingStream = this.pendingStreams.get(Integer.valueOf(i2));
        if (pendingStream == null) {
            pendingStream = new PendingStream(channelHandlerContext, i2);
            this.pendingStreams.put(Integer.valueOf(i2), pendingStream);
        }
        pendingStream.frames.add(new HeadersFrame(http2Headers, i3, s2, z2, i4, z3, channelPromise));
        return channelPromise;
    }

    @Override // io.netty.handler.codec.http2.DecoratingHttp2FrameWriter, io.netty.handler.codec.http2.Http2FrameWriter
    public ChannelFuture writeHeaders(ChannelHandlerContext channelHandlerContext, int i2, Http2Headers http2Headers, int i3, boolean z2, ChannelPromise channelPromise) {
        return writeHeaders(channelHandlerContext, i2, http2Headers, 0, (short) 16, false, i3, z2, channelPromise);
    }

    @Override // io.netty.handler.codec.http2.DecoratingHttp2FrameWriter, io.netty.handler.codec.http2.Http2FrameWriter
    public ChannelFuture writeRstStream(ChannelHandlerContext channelHandlerContext, int i2, long j2, ChannelPromise channelPromise) {
        if (isExistingStream(i2)) {
            return super.writeRstStream(channelHandlerContext, i2, j2, channelPromise);
        }
        PendingStream pendingStreamRemove = this.pendingStreams.remove(Integer.valueOf(i2));
        if (pendingStreamRemove != null) {
            pendingStreamRemove.close(null);
            channelPromise.setSuccess();
        } else {
            channelPromise.setFailure((Throwable) Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Stream does not exist %d", Integer.valueOf(i2)));
        }
        return channelPromise;
    }
}
