package io.netty.handler.codec.compression;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ChannelPromiseNotifier;
import io.netty.handler.codec.EncoderException;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.ThrowableUtil;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.zip.Checksum;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Exception;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.xxhash.XXHashFactory;

/* JADX INFO: loaded from: classes.dex */
public class Lz4FrameEncoder extends MessageToByteEncoder<ByteBuf> {
    public static final int DEFAULT_MAX_ENCODE_SIZE = Integer.MAX_VALUE;
    private static final EncoderException ENCODE_FINSHED_EXCEPTION = (EncoderException) ThrowableUtil.unknownStackTrace(new EncoderException(new IllegalStateException("encode finished and not enough space to write remaining data")), Lz4FrameEncoder.class, "encode");
    private final int blockSize;
    private ByteBuf buffer;
    private final ByteBufChecksum checksum;
    private final int compressionLevel;
    private final LZ4Compressor compressor;
    private volatile ChannelHandlerContext ctx;
    private volatile boolean finished;
    private final int maxEncodeSize;

    public Lz4FrameEncoder() {
        this(false);
    }

    public Lz4FrameEncoder(LZ4Factory lZ4Factory, boolean z2, int i2, Checksum checksum) {
        this(lZ4Factory, z2, i2, checksum, Integer.MAX_VALUE);
    }

    public Lz4FrameEncoder(LZ4Factory lZ4Factory, boolean z2, int i2, Checksum checksum, int i3) {
        Objects.requireNonNull(lZ4Factory, "factory");
        Objects.requireNonNull(checksum, "checksum");
        this.compressor = z2 ? lZ4Factory.highCompressor() : lZ4Factory.fastCompressor();
        this.checksum = ByteBufChecksum.wrapChecksum(checksum);
        this.compressionLevel = compressionLevel(i2);
        this.blockSize = i2;
        this.maxEncodeSize = ObjectUtil.checkPositive(i3, "maxEncodeSize");
        this.finished = false;
    }

    public Lz4FrameEncoder(boolean z2) {
        this(LZ4Factory.fastestInstance(), z2, 65536, XXHashFactory.fastestInstance().newStreamingHash32(Lz4Constants.DEFAULT_SEED).asChecksum());
    }

    private ByteBuf allocateBuffer(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, boolean z2, boolean z3) {
        int i2 = this.buffer.readableBytes() + byteBuf.readableBytes();
        if (i2 < 0) {
            throw new EncoderException("too much data to allocate a buffer for compression");
        }
        int iMaxCompressedLength = 0;
        while (i2 > 0) {
            int iMin = Math.min(this.blockSize, i2);
            i2 -= iMin;
            iMaxCompressedLength += this.compressor.maxCompressedLength(iMin) + 21;
        }
        if (iMaxCompressedLength > this.maxEncodeSize || iMaxCompressedLength < 0) {
            throw new EncoderException(String.format("requested encode buffer size (%d bytes) exceeds the maximum allowable size (%d bytes)", Integer.valueOf(iMaxCompressedLength), Integer.valueOf(this.maxEncodeSize)));
        }
        if (z3 && iMaxCompressedLength < this.blockSize) {
            return Unpooled.EMPTY_BUFFER;
        }
        ByteBufAllocator byteBufAllocatorAlloc = channelHandlerContext.alloc();
        return z2 ? byteBufAllocatorAlloc.ioBuffer(iMaxCompressedLength, iMaxCompressedLength) : byteBufAllocatorAlloc.heapBuffer(iMaxCompressedLength, iMaxCompressedLength);
    }

    private static int compressionLevel(int i2) {
        if (i2 < 64 || i2 > 33554432) {
            throw new IllegalArgumentException(String.format("blockSize: %d (expected: %d-%d)", Integer.valueOf(i2), 64, Integer.valueOf(Lz4Constants.MAX_BLOCK_SIZE)));
        }
        return Math.max(0, (32 - Integer.numberOfLeadingZeros(i2 - 1)) - 10);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public ChannelHandlerContext ctx() {
        ChannelHandlerContext channelHandlerContext = this.ctx;
        if (channelHandlerContext != null) {
            return channelHandlerContext;
        }
        throw new IllegalStateException("not added to a pipeline");
    }

    /* JADX INFO: Access modifiers changed from: private */
    public ChannelFuture finishEncode(ChannelHandlerContext channelHandlerContext, ChannelPromise channelPromise) {
        if (this.finished) {
            channelPromise.setSuccess();
            return channelPromise;
        }
        this.finished = true;
        ByteBuf byteBufHeapBuffer = channelHandlerContext.alloc().heapBuffer(this.compressor.maxCompressedLength(this.buffer.readableBytes()) + 21);
        flushBufferedData(byteBufHeapBuffer);
        int iWriterIndex = byteBufHeapBuffer.writerIndex();
        byteBufHeapBuffer.setLong(iWriterIndex, Lz4Constants.MAGIC_NUMBER);
        byteBufHeapBuffer.setByte(iWriterIndex + 8, (byte) (this.compressionLevel | 16));
        byteBufHeapBuffer.setInt(iWriterIndex + 9, 0);
        byteBufHeapBuffer.setInt(iWriterIndex + 13, 0);
        byteBufHeapBuffer.setInt(iWriterIndex + 17, 0);
        byteBufHeapBuffer.writerIndex(iWriterIndex + 21);
        return channelHandlerContext.writeAndFlush(byteBufHeapBuffer, channelPromise);
    }

    private void flushBufferedData(ByteBuf byteBuf) {
        int i2;
        int i3;
        int i4 = this.buffer.readableBytes();
        if (i4 == 0) {
            return;
        }
        this.checksum.reset();
        ByteBufChecksum byteBufChecksum = this.checksum;
        ByteBuf byteBuf2 = this.buffer;
        byteBufChecksum.update(byteBuf2, byteBuf2.readerIndex(), i4);
        int value = (int) this.checksum.getValue();
        byteBuf.ensureWritable(this.compressor.maxCompressedLength(i4) + 21);
        int iWriterIndex = byteBuf.writerIndex();
        int i5 = iWriterIndex + 21;
        try {
            ByteBuffer byteBufferInternalNioBuffer = byteBuf.internalNioBuffer(i5, byteBuf.writableBytes() - 21);
            int iPosition = byteBufferInternalNioBuffer.position();
            LZ4Compressor lZ4Compressor = this.compressor;
            ByteBuf byteBuf3 = this.buffer;
            lZ4Compressor.compress(byteBuf3.internalNioBuffer(byteBuf3.readerIndex(), i4), byteBufferInternalNioBuffer);
            int iPosition2 = byteBufferInternalNioBuffer.position() - iPosition;
            if (iPosition2 >= i4) {
                i3 = 16;
                byteBuf.setBytes(i5, this.buffer, 0, i4);
                i2 = i4;
            } else {
                i2 = iPosition2;
                i3 = 32;
            }
            byteBuf.setLong(iWriterIndex, Lz4Constants.MAGIC_NUMBER);
            byteBuf.setByte(iWriterIndex + 8, (byte) (i3 | this.compressionLevel));
            byteBuf.setIntLE(iWriterIndex + 9, i2);
            byteBuf.setIntLE(iWriterIndex + 13, i4);
            byteBuf.setIntLE(iWriterIndex + 17, value);
            byteBuf.writerIndex(i5 + i2);
            this.buffer.clear();
        } catch (LZ4Exception e2) {
            throw new CompressionException((Throwable) e2);
        }
    }

    @Override // io.netty.handler.codec.MessageToByteEncoder
    public ByteBuf allocateBuffer(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, boolean z2) {
        return allocateBuffer(channelHandlerContext, byteBuf, z2, true);
    }

    public ChannelFuture close() {
        return close(ctx().newPromise());
    }

    public ChannelFuture close(final ChannelPromise channelPromise) {
        ChannelHandlerContext channelHandlerContextCtx = ctx();
        EventExecutor eventExecutorExecutor = channelHandlerContextCtx.executor();
        if (eventExecutorExecutor.inEventLoop()) {
            return finishEncode(channelHandlerContextCtx, channelPromise);
        }
        eventExecutorExecutor.execute(new Runnable() { // from class: io.netty.handler.codec.compression.Lz4FrameEncoder.1
            @Override // java.lang.Runnable
            public void run() {
                Lz4FrameEncoder lz4FrameEncoder = Lz4FrameEncoder.this;
                lz4FrameEncoder.finishEncode(lz4FrameEncoder.ctx(), channelPromise).addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelPromiseNotifier(channelPromise));
            }
        });
        return channelPromise;
    }

    @Override // io.netty.channel.ChannelOutboundHandlerAdapter, io.netty.channel.ChannelOutboundHandler
    public void close(final ChannelHandlerContext channelHandlerContext, final ChannelPromise channelPromise) {
        ChannelFuture channelFutureFinishEncode = finishEncode(channelHandlerContext, channelHandlerContext.newPromise());
        channelFutureFinishEncode.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelFutureListener() { // from class: io.netty.handler.codec.compression.Lz4FrameEncoder.2
            @Override // io.netty.util.concurrent.GenericFutureListener
            public void operationComplete(ChannelFuture channelFuture) {
                channelHandlerContext.close(channelPromise);
            }
        });
        if (channelFutureFinishEncode.isDone()) {
            return;
        }
        channelHandlerContext.executor().schedule(new Runnable() { // from class: io.netty.handler.codec.compression.Lz4FrameEncoder.3
            @Override // java.lang.Runnable
            public void run() {
                channelHandlerContext.close(channelPromise);
            }
        }, 10L, TimeUnit.SECONDS);
    }

    @Override // io.netty.handler.codec.MessageToByteEncoder
    public void encode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, ByteBuf byteBuf2) {
        if (this.finished) {
            if (!byteBuf2.isWritable(byteBuf.readableBytes())) {
                throw ENCODE_FINSHED_EXCEPTION;
            }
            byteBuf2.writeBytes(byteBuf);
        } else {
            ByteBuf byteBuf3 = this.buffer;
            while (true) {
                int i2 = byteBuf.readableBytes();
                if (i2 <= 0) {
                    return;
                }
                byteBuf.readBytes(byteBuf3, Math.min(i2, byteBuf3.writableBytes()));
                if (!byteBuf3.isWritable()) {
                    flushBufferedData(byteBuf2);
                }
            }
        }
    }

    @Override // io.netty.channel.ChannelOutboundHandlerAdapter, io.netty.channel.ChannelOutboundHandler
    public void flush(ChannelHandlerContext channelHandlerContext) {
        ByteBuf byteBuf = this.buffer;
        if (byteBuf != null && byteBuf.isReadable()) {
            ByteBuf byteBufAllocateBuffer = allocateBuffer(channelHandlerContext, Unpooled.EMPTY_BUFFER, isPreferDirect(), false);
            flushBufferedData(byteBufAllocateBuffer);
            channelHandlerContext.write(byteBufAllocateBuffer);
        }
        channelHandlerContext.flush();
    }

    public final ByteBuf getBackingBuffer() {
        return this.buffer;
    }

    @Override // io.netty.channel.ChannelHandlerAdapter, io.netty.channel.ChannelHandler
    public void handlerAdded(ChannelHandlerContext channelHandlerContext) {
        this.ctx = channelHandlerContext;
        ByteBuf byteBufWrappedBuffer = Unpooled.wrappedBuffer(new byte[this.blockSize]);
        this.buffer = byteBufWrappedBuffer;
        byteBufWrappedBuffer.clear();
    }

    @Override // io.netty.channel.ChannelHandlerAdapter, io.netty.channel.ChannelHandler
    public void handlerRemoved(ChannelHandlerContext channelHandlerContext) {
        super.handlerRemoved(channelHandlerContext);
        ByteBuf byteBuf = this.buffer;
        if (byteBuf != null) {
            byteBuf.release();
            this.buffer = null;
        }
    }

    public boolean isClosed() {
        return this.finished;
    }
}
