package androidx.media3.datasource.okhttp;

import E3.k;
import G3.g;
import J3.C;
import android.net.Uri;
import androidx.media3.common.MediaLibraryInfo;
import androidx.media3.common.util.Assertions;
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 java.io.EOFException;
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.TreeMap;
import java.util.concurrent.ExecutionException;
import kotlin.jvm.internal.o;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.RequestBody$Companion$toRequestBody$2;
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;
    private final CacheControl cacheControl;
    private final Call.Factory callFactory;
    private final k contentTypePredicate;
    private DataSpec dataSpec;
    private final HttpDataSource.RequestProperties defaultRequestProperties;
    private boolean opened;
    private final HttpDataSource.RequestProperties requestProperties;
    private Response response;
    private InputStream responseByteStream;
    private final String userAgent;

    public static final class Factory implements HttpDataSource.Factory {
        private CacheControl cacheControl;
        private final Call.Factory callFactory;
        private k contentTypePredicate;
        private final HttpDataSource.RequestProperties defaultRequestProperties = new HttpDataSource.RequestProperties();
        private TransferListener transferListener;
        private String userAgent;

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

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

        @UnstableApi
        public Factory setContentTypePredicate(k kVar) {
            this.contentTypePredicate = kVar;
            return this;
        }

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

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

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

        @Override // androidx.media3.datasource.HttpDataSource.Factory
        @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) Assertions.checkNotNull(response.f22146j)).close();
            this.response = null;
        }
        this.responseByteStream = null;
    }

    private Response executeCall(Call call) throws IOException {
        final C c6 = new C();
        call.g(new Callback() { // from class: androidx.media3.datasource.okhttp.OkHttpDataSource.1
            @Override // okhttp3.Callback
            public void onFailure(Call call2, IOException iOException) {
                c6.k(iOException);
            }

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

    private Request makeRequest(DataSpec dataSpec) throws HttpDataSource.HttpDataSourceException, EOFException {
        HttpUrl httpUrlA;
        long j4 = dataSpec.position;
        long j6 = dataSpec.length;
        String string = dataSpec.uri.toString();
        HttpUrl.f22023k.getClass();
        o.h(string, "<this>");
        RequestBody$Companion$toRequestBody$2 requestBody$Companion$toRequestBody$2B = null;
        try {
            HttpUrl.Builder builder = new HttpUrl.Builder();
            builder.b(null, string);
            httpUrlA = builder.a();
        } catch (IllegalArgumentException unused) {
            httpUrlA = null;
        }
        if (httpUrlA == null) {
            throw new HttpDataSource.HttpDataSourceException("Malformed URL", dataSpec, 1004, 1);
        }
        Request.Builder builder2 = new Request.Builder();
        builder2.f22131a = httpUrlA;
        CacheControl cacheControl = this.cacheControl;
        if (cacheControl != null) {
            builder2.c(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()) {
            builder2.e((String) entry.getKey(), (String) entry.getValue());
        }
        String strBuildRangeRequestHeader = HttpUtil.buildRangeRequestHeader(j4, j6);
        if (strBuildRangeRequestHeader != null) {
            builder2.a("Range", strBuildRangeRequestHeader);
        }
        String str = this.userAgent;
        if (str != null) {
            builder2.a("User-Agent", str);
        }
        if (!dataSpec.isFlagSet(1)) {
            builder2.a("Accept-Encoding", "identity");
        }
        byte[] bArr = dataSpec.httpBody;
        if (bArr != null) {
            RequestBody.Companion companion = RequestBody.f22136a;
            companion.getClass();
            requestBody$Companion$toRequestBody$2B = RequestBody.Companion.b(companion, bArr, null, 7);
        } else if (dataSpec.httpMethod == 2) {
            byte[] bArr2 = Util.EMPTY_BYTE_ARRAY;
            RequestBody.Companion companion2 = RequestBody.f22136a;
            companion2.getClass();
            o.h(bArr2, "<this>");
            requestBody$Companion$toRequestBody$2B = RequestBody.Companion.b(companion2, bArr2, null, 7);
        }
        builder2.g(dataSpec.getHttpMethodString(), requestBody$Companion$toRequestBody$2B);
        return builder2.b();
    }

    private int readInternal(byte[] bArr, int i6, int i7) throws IOException {
        if (i7 == 0) {
            return 0;
        }
        long j4 = this.bytesToRead;
        if (j4 != -1) {
            long j6 = j4 - this.bytesRead;
            if (j6 == 0) {
                return -1;
            }
            i7 = (int) Math.min(i7, j6);
        }
        int i8 = ((InputStream) Util.castNonNull(this.responseByteStream)).read(bArr, i6, i7);
        if (i8 == -1) {
            return -1;
        }
        this.bytesRead += (long) i8;
        bytesTransferred(i8);
        return i8;
    }

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

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

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

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

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

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

    @Override // androidx.media3.datasource.DataSource
    @UnstableApi
    public Uri getUri() {
        Response response = this.response;
        if (response == null) {
            return null;
        }
        return Uri.parse(response.f22140a.f22125a.f22032i);
    }

    /* JADX WARN: Removed duplicated region for block: B:40:0x00b7  */
    @Override // androidx.media3.datasource.DataSource
    @UnstableApi
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public long open(DataSpec dataSpec) throws HttpDataSource.HttpDataSourceException {
        long j4;
        byte[] bArrB;
        this.dataSpec = dataSpec;
        this.bytesRead = 0L;
        this.bytesToRead = 0L;
        transferInitializing(dataSpec);
        try {
            Response responseExecuteCall = executeCall(this.callFactory.a(makeRequest(dataSpec)));
            this.response = responseExecuteCall;
            ResponseBody responseBody = (ResponseBody) Assertions.checkNotNull(responseExecuteCall.f22146j);
            this.responseByteStream = responseBody.c().x();
            boolean zC = responseExecuteCall.c();
            int i6 = responseExecuteCall.f22143d;
            if (!zC) {
                Headers headers = responseExecuteCall.f22145f;
                if (i6 == 416) {
                    if (dataSpec.position == HttpUtil.getDocumentSize(headers.g("Content-Range"))) {
                        this.opened = true;
                        transferStarted(dataSpec);
                        long j6 = dataSpec.length;
                        if (j6 != -1) {
                            return j6;
                        }
                        return 0L;
                    }
                }
                try {
                    bArrB = g.b((InputStream) Assertions.checkNotNull(this.responseByteStream));
                } catch (IOException unused) {
                    bArrB = Util.EMPTY_BYTE_ARRAY;
                }
                byte[] bArr = bArrB;
                TreeMap treeMapK = headers.k();
                closeConnectionQuietly();
                throw new HttpDataSource.InvalidResponseCodeException(i6, responseExecuteCall.f22142c, i6 == 416 ? new DataSourceException(2008) : null, treeMapK, dataSpec, bArr);
            }
            MediaType mediaTypeB = responseBody.b();
            String str = mediaTypeB != null ? mediaTypeB.f22046a : "";
            k kVar = this.contentTypePredicate;
            if (kVar != null && !kVar.apply(str)) {
                closeConnectionQuietly();
                throw new HttpDataSource.InvalidContentTypeException(str, dataSpec);
            }
            if (i6 == 200) {
                j4 = dataSpec.position;
                if (j4 == 0) {
                    j4 = 0;
                }
            }
            long j7 = dataSpec.length;
            if (j7 != -1) {
                this.bytesToRead = j7;
            } else {
                long jA = responseBody.a();
                this.bytesToRead = jA != -1 ? jA - j4 : -1L;
            }
            this.opened = true;
            transferStarted(dataSpec);
            try {
                skipFully(j4, dataSpec);
                return this.bytesToRead;
            } catch (HttpDataSource.HttpDataSourceException e6) {
                closeConnectionQuietly();
                throw e6;
            }
        } catch (IOException e7) {
            throw HttpDataSource.HttpDataSourceException.createForIOException(e7, dataSpec, 1);
        }
    }

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

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

    private OkHttpDataSource(Call.Factory factory, String str, CacheControl cacheControl, HttpDataSource.RequestProperties requestProperties, k kVar) {
        super(true);
        this.callFactory = (Call.Factory) Assertions.checkNotNull(factory);
        this.userAgent = str;
        this.cacheControl = cacheControl;
        this.defaultRequestProperties = requestProperties;
        this.contentTypePredicate = kVar;
        this.requestProperties = new HttpDataSource.RequestProperties();
    }
}
