package androidx.media3.datasource.okhttp;

import android.net.Uri;
import androidx.media3.common.MediaLibraryInfo;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import androidx.media3.datasource.BaseDataSource;
import androidx.media3.datasource.DataSourceException;
import androidx.media3.datasource.DataSpec;
import androidx.media3.datasource.HttpDataSource;
import androidx.media3.datasource.HttpUtil;
import androidx.media3.datasource.TransferListener;
import androidx.media3.exoplayer.rtsp.RtspHeaders;
import defpackage.hs0;
import defpackage.om8;
import defpackage.pf7;
import defpackage.rq6;
import defpackage.to0;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/* JADX INFO: loaded from: classes.dex */
public class OkHttpDataSource extends BaseDataSource implements HttpDataSource {
    private long bytesRead;
    private long bytesToRead;

    @rq6
    private final CacheControl cacheControl;
    private final Call.Factory callFactory;
    private boolean connectionEstablished;

    @rq6
    private final pf7<String> contentTypePredicate;

    @rq6
    private DataSpec dataSpec;

    @rq6
    private final HttpDataSource.RequestProperties defaultRequestProperties;
    private final HttpDataSource.RequestProperties requestProperties;

    @rq6
    private Response response;

    @rq6
    private InputStream responseByteStream;

    @rq6
    private final String userAgent;

    public static final class Factory implements HttpDataSource.Factory {

        @rq6
        private CacheControl cacheControl;
        private final Call.Factory callFactory;

        @rq6
        private pf7<String> contentTypePredicate;
        private final HttpDataSource.RequestProperties defaultRequestProperties = new HttpDataSource.RequestProperties();

        @rq6
        private TransferListener transferListener;

        @rq6
        private String userAgent;

        public Factory(Call.Factory factory) {
            this.callFactory = factory;
        }

        @hs0
        @UnstableApi
        public Factory setCacheControl(@rq6 CacheControl cacheControl) {
            this.cacheControl = cacheControl;
            return this;
        }

        @hs0
        @UnstableApi
        public Factory setContentTypePredicate(@rq6 pf7<String> pf7Var) {
            this.contentTypePredicate = pf7Var;
            return this;
        }

        @Override // androidx.media3.datasource.HttpDataSource.Factory
        @hs0
        @UnstableApi
        public /* bridge */ /* synthetic */ HttpDataSource.Factory setDefaultRequestProperties(Map map) {
            return setDefaultRequestProperties((Map<String, String>) map);
        }

        @hs0
        @UnstableApi
        public Factory setTransferListener(@rq6 TransferListener transferListener) {
            this.transferListener = transferListener;
            return this;
        }

        @hs0
        public Factory setUserAgent(@rq6 String str) {
            this.userAgent = str;
            return this;
        }

        @Override // androidx.media3.datasource.HttpDataSource.Factory
        @hs0
        @UnstableApi
        public final Factory setDefaultRequestProperties(Map<String, String> map) {
            this.defaultRequestProperties.clearAndSet(map);
            return this;
        }

        @Override // androidx.media3.datasource.HttpDataSource.Factory, androidx.media3.datasource.DataSource.Factory
        @UnstableApi
        public OkHttpDataSource createDataSource() {
            OkHttpDataSource okHttpDataSource = new OkHttpDataSource(this.callFactory, this.userAgent, this.cacheControl, this.defaultRequestProperties, this.contentTypePredicate);
            TransferListener transferListener = this.transferListener;
            if (transferListener != null) {
                okHttpDataSource.addTransferListener(transferListener);
            }
            return okHttpDataSource;
        }
    }

    static {
        MediaLibraryInfo.registerModule("media3.datasource.okhttp");
    }

    private void closeConnectionQuietly() {
        Response response = this.response;
        if (response != null) {
            ResponseBody responseBodyBody = response.body();
            responseBodyBody.getClass();
            responseBodyBody.close();
        }
        this.responseByteStream = null;
    }

    /* JADX WARN: Multi-variable type inference failed */
    private Response executeCall(Call call) throws IOException {
        final om8 om8Var = new om8();
        call.enqueue(new Callback() { // from class: androidx.media3.datasource.okhttp.OkHttpDataSource.1
            @Override // okhttp3.Callback
            public void onFailure(Call call2, IOException iOException) {
                om8Var.setException(iOException);
            }

            @Override // okhttp3.Callback
            public void onResponse(Call call2, Response response) {
                om8Var.set(response);
            }
        });
        try {
            return (Response) om8Var.get();
        } catch (InterruptedException unused) {
            call.cancel();
            throw new InterruptedIOException();
        } catch (ExecutionException e) {
            throw new IOException(e);
        }
    }

    private Request makeRequest(DataSpec dataSpec) throws HttpDataSource.HttpDataSourceException {
        long j = dataSpec.position;
        long j2 = dataSpec.length;
        HttpUrl httpUrl = HttpUrl.parse(dataSpec.uri.toString());
        if (httpUrl == null) {
            throw new HttpDataSource.HttpDataSourceException("Malformed URL", dataSpec, 1004, 1);
        }
        Request.Builder builderUrl = new Request.Builder().url(httpUrl);
        CacheControl cacheControl = this.cacheControl;
        if (cacheControl != null) {
            builderUrl.cacheControl(cacheControl);
        }
        HashMap map = new HashMap();
        HttpDataSource.RequestProperties requestProperties = this.defaultRequestProperties;
        if (requestProperties != null) {
            map.putAll(requestProperties.getSnapshot());
        }
        map.putAll(this.requestProperties.getSnapshot());
        map.putAll(dataSpec.httpRequestHeaders);
        for (Map.Entry entry : map.entrySet()) {
            builderUrl.header((String) entry.getKey(), (String) entry.getValue());
        }
        String strBuildRangeRequestHeader = HttpUtil.buildRangeRequestHeader(j, j2);
        if (strBuildRangeRequestHeader != null) {
            builderUrl.addHeader(RtspHeaders.RANGE, strBuildRangeRequestHeader);
        }
        String str = this.userAgent;
        if (str != null) {
            builderUrl.addHeader(RtspHeaders.USER_AGENT, str);
        }
        if (!dataSpec.isFlagSet(1)) {
            builderUrl.addHeader("Accept-Encoding", "identity");
        }
        byte[] bArr = dataSpec.httpBody;
        builderUrl.method(dataSpec.getHttpMethodString(), bArr != null ? RequestBody.create(bArr) : dataSpec.httpMethod == 2 ? RequestBody.create(Util.EMPTY_BYTE_ARRAY) : null);
        return builderUrl.build();
    }

    private int readInternal(byte[] bArr, int i, int i2) throws IOException {
        if (i2 == 0) {
            return 0;
        }
        long j = this.bytesToRead;
        if (j != -1) {
            long j2 = j - this.bytesRead;
            if (j2 == 0) {
                return -1;
            }
            i2 = (int) Math.min(i2, j2);
        }
        int i3 = ((InputStream) Util.castNonNull(this.responseByteStream)).read(bArr, i, i2);
        if (i3 == -1) {
            return -1;
        }
        this.bytesRead += (long) i3;
        bytesTransferred(i3);
        return i3;
    }

    private void skipFully(long j, DataSpec dataSpec) throws HttpDataSource.HttpDataSourceException {
        if (j == 0) {
            return;
        }
        byte[] bArr = new byte[4096];
        while (j > 0) {
            try {
                int i = ((InputStream) Util.castNonNull(this.responseByteStream)).read(bArr, 0, (int) Math.min(j, 4096));
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedIOException();
                }
                if (i == -1) {
                    throw new HttpDataSource.HttpDataSourceException(dataSpec, 2008, 1);
                }
                j -= (long) i;
                bytesTransferred(i);
            } catch (IOException e) {
                if (!(e instanceof HttpDataSource.HttpDataSourceException)) {
                    throw new HttpDataSource.HttpDataSourceException(dataSpec, 2000, 1);
                }
                throw ((HttpDataSource.HttpDataSourceException) e);
            }
        }
    }

    @Override // androidx.media3.datasource.HttpDataSource
    @UnstableApi
    public void clearAllRequestProperties() {
        this.requestProperties.clear();
    }

    @Override // androidx.media3.datasource.HttpDataSource
    @UnstableApi
    public void clearRequestProperty(String str) {
        str.getClass();
        this.requestProperties.remove(str);
    }

    @Override // androidx.media3.datasource.DataSource
    @UnstableApi
    public void close() {
        if (this.connectionEstablished) {
            this.connectionEstablished = false;
            transferEnded();
            closeConnectionQuietly();
        }
        this.response = null;
        this.dataSpec = null;
    }

    @Override // androidx.media3.datasource.HttpDataSource
    @UnstableApi
    public int getResponseCode() {
        Response response = this.response;
        if (response == null) {
            return -1;
        }
        return response.code();
    }

    @Override // androidx.media3.datasource.DataSource
    @UnstableApi
    public Map<String, List<String>> getResponseHeaders() {
        Response response = this.response;
        return response == null ? Collections.EMPTY_MAP : response.headers().toMultimap();
    }

    @Override // androidx.media3.datasource.DataSource
    @rq6
    @UnstableApi
    public Uri getUri() {
        Response response = this.response;
        if (response != null) {
            return Uri.parse(response.request().url().getUrl());
        }
        DataSpec dataSpec = this.dataSpec;
        if (dataSpec != null) {
            return dataSpec.uri;
        }
        return null;
    }

    @Override // androidx.media3.datasource.DataSource
    @UnstableApi
    public long open(DataSpec dataSpec) throws HttpDataSource.HttpDataSourceException {
        byte[] bArrC;
        this.dataSpec = dataSpec;
        long j = 0;
        this.bytesRead = 0L;
        this.bytesToRead = 0L;
        transferInitializing(dataSpec);
        try {
            Response responseExecuteCall = executeCall(this.callFactory.newCall(makeRequest(dataSpec)));
            this.response = responseExecuteCall;
            ResponseBody responseBodyBody = responseExecuteCall.body();
            responseBodyBody.getClass();
            this.responseByteStream = responseBodyBody.byteStream();
            int iCode = responseExecuteCall.code();
            if (!responseExecuteCall.isSuccessful()) {
                if (iCode == 416) {
                    if (dataSpec.position == HttpUtil.getDocumentSize(responseExecuteCall.headers().get("Content-Range"))) {
                        this.connectionEstablished = true;
                        transferStarted(dataSpec);
                        long j2 = dataSpec.length;
                        if (j2 != -1) {
                            return j2;
                        }
                        return 0L;
                    }
                }
                try {
                    InputStream inputStream = this.responseByteStream;
                    inputStream.getClass();
                    bArrC = to0.c(inputStream);
                } catch (IOException unused) {
                    bArrC = Util.EMPTY_BYTE_ARRAY;
                }
                byte[] bArr = bArrC;
                Map<String, List<String>> multimap = responseExecuteCall.headers().toMultimap();
                closeConnectionQuietly();
                throw new HttpDataSource.InvalidResponseCodeException(iCode, responseExecuteCall.message(), iCode == 416 ? new DataSourceException(2008) : null, multimap, dataSpec, bArr);
            }
            MediaType mediaType = responseBodyBody.get$contentType();
            String mediaType2 = mediaType != null ? mediaType.getMediaType() : "";
            pf7<String> pf7Var = this.contentTypePredicate;
            if (pf7Var != null && !pf7Var.apply(mediaType2)) {
                closeConnectionQuietly();
                throw new HttpDataSource.InvalidContentTypeException(mediaType2, dataSpec);
            }
            if (iCode == 200) {
                long j3 = dataSpec.position;
                if (j3 != 0) {
                    j = j3;
                }
            }
            long j4 = dataSpec.length;
            if (j4 != -1) {
                this.bytesToRead = j4;
            } else {
                long contentLength = responseBodyBody.getContentLength();
                this.bytesToRead = contentLength != -1 ? contentLength - j : -1L;
            }
            this.connectionEstablished = true;
            transferStarted(dataSpec);
            try {
                skipFully(j, dataSpec);
                return this.bytesToRead;
            } catch (HttpDataSource.HttpDataSourceException e) {
                closeConnectionQuietly();
                throw e;
            }
        } catch (IOException e2) {
            throw HttpDataSource.HttpDataSourceException.createForIOException(e2, dataSpec, 1);
        }
    }

    @Override // androidx.media3.common.DataReader
    @UnstableApi
    public int read(byte[] bArr, int i, int i2) throws HttpDataSource.HttpDataSourceException {
        try {
            return readInternal(bArr, i, i2);
        } catch (IOException e) {
            throw HttpDataSource.HttpDataSourceException.createForIOException(e, (DataSpec) Util.castNonNull(this.dataSpec), 2);
        }
    }

    @Override // androidx.media3.datasource.HttpDataSource
    @UnstableApi
    public void setRequestProperty(String str, String str2) {
        str.getClass();
        str2.getClass();
        this.requestProperties.set(str, str2);
    }

    private OkHttpDataSource(Call.Factory factory, @rq6 String str, @rq6 CacheControl cacheControl, @rq6 HttpDataSource.RequestProperties requestProperties, @rq6 pf7<String> pf7Var) {
        super(true);
        factory.getClass();
        this.callFactory = factory;
        this.userAgent = str;
        this.cacheControl = cacheControl;
        this.defaultRequestProperties = requestProperties;
        this.contentTypePredicate = pf7Var;
        this.requestProperties = new HttpDataSource.RequestProperties();
    }
}
