package androidx.media3.exoplayer.ima;

import android.content.Context;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.media3.common.AdViewProvider;
import androidx.media3.common.MediaLibraryInfo;
import androidx.media3.common.MimeTypes;
import androidx.media3.common.Player;
import androidx.media3.common.Timeline;
import androidx.media3.common.util.Assertions;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import androidx.media3.datasource.DataSpec;
import androidx.media3.exoplayer.ima.ImaUtil;
import androidx.media3.exoplayer.source.ads.AdsLoader;
import androidx.media3.exoplayer.source.ads.AdsMediaSource;
import com.google.ads.interactivemedia.v3.api.AdDisplayContainer;
import com.google.ads.interactivemedia.v3.api.AdErrorEvent;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.google.ads.interactivemedia.v3.api.AdsRenderingSettings;
import com.google.ads.interactivemedia.v3.api.AdsRequest;
import com.google.ads.interactivemedia.v3.api.CompanionAdSlot;
import com.google.ads.interactivemedia.v3.api.FriendlyObstruction;
import com.google.ads.interactivemedia.v3.api.FriendlyObstructionPurpose;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;
import com.google.ads.interactivemedia.v3.api.UiElement;
import com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import tv.danmaku.ijk.media.player.IjkMediaMeta;

/* JADX INFO: loaded from: classes.dex */
public final class ImaAdsLoader implements AdsLoader {
    private final HashMap<Object, AdTagLoader> adTagLoaderByAdsId;
    private final HashMap<AdsMediaSource, AdTagLoader> adTagLoaderByAdsMediaSource;
    private final ImaUtil.Configuration configuration;
    private final Context context;

    @Nullable
    private AdTagLoader currentAdTagLoader;
    private final ImaUtil.ImaFactory imaFactory;

    @Nullable
    private Player nextPlayer;
    private final Timeline.Period period;

    @Nullable
    private Player player;
    private final PlayerListenerImpl playerListener;
    private List<String> supportedMimeTypes;
    private boolean wasSetPlayerCalled;
    private final Timeline.Window window;

    public static final class Builder {

        @UnstableApi
        public static final long DEFAULT_AD_PRELOAD_TIMEOUT_MS = 10000;

        @Nullable
        private AdErrorEvent.AdErrorListener adErrorListener;

        @Nullable
        private AdEvent.AdEventListener adEventListener;

        @Nullable
        private List<String> adMediaMimeTypes;

        @Nullable
        private Set<UiElement> adUiElements;

        @Nullable
        private Collection<CompanionAdSlot> companionAdSlots;
        private final Context context;
        private boolean debugModeEnabled;

        @Nullable
        private Boolean enableContinuousPlayback;

        @Nullable
        private ImaSdkSettings imaSdkSettings;

        @Nullable
        private VideoAdPlayer.VideoAdPlayerCallback videoAdPlayerCallback;
        private long adPreloadTimeoutMs = 10000;
        private int vastLoadTimeoutMs = -1;
        private int mediaLoadTimeoutMs = -1;
        private int mediaBitrate = -1;
        private boolean focusSkipButtonWhenAvailable = true;
        private boolean playAdBeforeStartPosition = true;
        private ImaUtil.ImaFactory imaFactory = new DefaultImaFactory();

        public Builder(Context context) {
            this.context = ((Context) Assertions.checkNotNull(context)).getApplicationContext();
        }

        public ImaAdsLoader build() {
            int i10 = this.vastLoadTimeoutMs;
            if (i10 != -1 && this.adPreloadTimeoutMs < i10) {
                this.adPreloadTimeoutMs = i10;
            }
            return new ImaAdsLoader(this.context, new ImaUtil.Configuration(this.adPreloadTimeoutMs, this.vastLoadTimeoutMs, this.mediaLoadTimeoutMs, this.focusSkipButtonWhenAvailable, this.playAdBeforeStartPosition, this.mediaBitrate, this.enableContinuousPlayback, this.adMediaMimeTypes, this.adUiElements, this.companionAdSlots, this.adErrorListener, this.adEventListener, this.videoAdPlayerCallback, this.imaSdkSettings, this.debugModeEnabled), this.imaFactory);
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setAdErrorListener(AdErrorEvent.AdErrorListener adErrorListener) {
            this.adErrorListener = (AdErrorEvent.AdErrorListener) Assertions.checkNotNull(adErrorListener);
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setAdEventListener(AdEvent.AdEventListener adEventListener) {
            this.adEventListener = (AdEvent.AdEventListener) Assertions.checkNotNull(adEventListener);
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setAdMediaMimeTypes(List<String> list) {
            this.adMediaMimeTypes = ImmutableList.p((Collection) Assertions.checkNotNull(list));
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setAdPreloadTimeoutMs(long j10) {
            Assertions.checkArgument(j10 == -9223372036854775807L || j10 > 0);
            this.adPreloadTimeoutMs = j10;
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setAdUiElements(Set<UiElement> set) {
            this.adUiElements = ImmutableSet.o((Collection) Assertions.checkNotNull(set));
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setCompanionAdSlots(Collection<CompanionAdSlot> collection) {
            this.companionAdSlots = ImmutableList.p((Collection) Assertions.checkNotNull(collection));
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setDebugModeEnabled(boolean z10) {
            this.debugModeEnabled = z10;
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setEnableContinuousPlayback(boolean z10) {
            this.enableContinuousPlayback = Boolean.valueOf(z10);
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setFocusSkipButtonWhenAvailable(boolean z10) {
            this.focusSkipButtonWhenAvailable = z10;
            return this;
        }

        @CanIgnoreReturnValue
        @VisibleForTesting
        public Builder setImaFactory(ImaUtil.ImaFactory imaFactory) {
            this.imaFactory = (ImaUtil.ImaFactory) Assertions.checkNotNull(imaFactory);
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setImaSdkSettings(ImaSdkSettings imaSdkSettings) {
            this.imaSdkSettings = (ImaSdkSettings) Assertions.checkNotNull(imaSdkSettings);
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setMaxMediaBitrate(@IntRange(from = IjkMediaMeta.AV_CH_FRONT_LEFT) int i10) {
            Assertions.checkArgument(i10 > 0);
            this.mediaBitrate = i10;
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setMediaLoadTimeoutMs(@IntRange(from = IjkMediaMeta.AV_CH_FRONT_LEFT) int i10) {
            Assertions.checkArgument(i10 > 0);
            this.mediaLoadTimeoutMs = i10;
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setPlayAdBeforeStartPosition(boolean z10) {
            this.playAdBeforeStartPosition = z10;
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setVastLoadTimeoutMs(@IntRange(from = IjkMediaMeta.AV_CH_FRONT_LEFT) int i10) {
            Assertions.checkArgument(i10 > 0);
            this.vastLoadTimeoutMs = i10;
            return this;
        }

        @CanIgnoreReturnValue
        @UnstableApi
        public Builder setVideoAdPlayerCallback(VideoAdPlayer.VideoAdPlayerCallback videoAdPlayerCallback) {
            this.videoAdPlayerCallback = (VideoAdPlayer.VideoAdPlayerCallback) Assertions.checkNotNull(videoAdPlayerCallback);
            return this;
        }
    }

    public static final class DefaultImaFactory implements ImaUtil.ImaFactory {
        private DefaultImaFactory() {
        }

        @Override // androidx.media3.exoplayer.ima.ImaUtil.ImaFactory
        public AdDisplayContainer createAdDisplayContainer(ViewGroup viewGroup, VideoAdPlayer videoAdPlayer) {
            return ImaSdkFactory.createAdDisplayContainer(viewGroup, videoAdPlayer);
        }

        @Override // androidx.media3.exoplayer.ima.ImaUtil.ImaFactory
        public com.google.ads.interactivemedia.v3.api.AdsLoader createAdsLoader(Context context, ImaSdkSettings imaSdkSettings, AdDisplayContainer adDisplayContainer) {
            return ImaSdkFactory.getInstance().createAdsLoader(context, imaSdkSettings, adDisplayContainer);
        }

        @Override // androidx.media3.exoplayer.ima.ImaUtil.ImaFactory
        public AdsRenderingSettings createAdsRenderingSettings() {
            return ImaSdkFactory.getInstance().createAdsRenderingSettings();
        }

        @Override // androidx.media3.exoplayer.ima.ImaUtil.ImaFactory
        public AdsRequest createAdsRequest() {
            return ImaSdkFactory.getInstance().createAdsRequest();
        }

        @Override // androidx.media3.exoplayer.ima.ImaUtil.ImaFactory
        public AdDisplayContainer createAudioAdDisplayContainer(Context context, VideoAdPlayer videoAdPlayer) {
            return ImaSdkFactory.createAudioAdDisplayContainer(context, videoAdPlayer);
        }

        @Override // androidx.media3.exoplayer.ima.ImaUtil.ImaFactory
        public FriendlyObstruction createFriendlyObstruction(View view, FriendlyObstructionPurpose friendlyObstructionPurpose, @Nullable String str) {
            return ImaSdkFactory.getInstance().createFriendlyObstruction(view, friendlyObstructionPurpose, str);
        }

        @Override // androidx.media3.exoplayer.ima.ImaUtil.ImaFactory
        public ImaSdkSettings createImaSdkSettings() {
            ImaSdkSettings imaSdkSettingsCreateImaSdkSettings = ImaSdkFactory.getInstance().createImaSdkSettings();
            imaSdkSettingsCreateImaSdkSettings.setLanguage(Util.getSystemLanguageCodes()[0]);
            return imaSdkSettingsCreateImaSdkSettings;
        }
    }

    public final class PlayerListenerImpl implements Player.Listener {
        private PlayerListenerImpl() {
        }

        @Override // androidx.media3.common.Player.Listener
        public void onPositionDiscontinuity(Player.PositionInfo positionInfo, Player.PositionInfo positionInfo2, int i10) {
            ImaAdsLoader.this.maybeUpdateCurrentAdTagLoader();
            ImaAdsLoader.this.maybePreloadNextPeriodAds();
        }

        @Override // androidx.media3.common.Player.Listener
        public void onRepeatModeChanged(int i10) {
            ImaAdsLoader.this.maybePreloadNextPeriodAds();
        }

        @Override // androidx.media3.common.Player.Listener
        public void onShuffleModeEnabledChanged(boolean z10) {
            ImaAdsLoader.this.maybePreloadNextPeriodAds();
        }

        @Override // androidx.media3.common.Player.Listener
        public void onTimelineChanged(Timeline timeline, int i10) {
            if (timeline.isEmpty()) {
                return;
            }
            ImaAdsLoader.this.maybeUpdateCurrentAdTagLoader();
            ImaAdsLoader.this.maybePreloadNextPeriodAds();
        }
    }

    static {
        MediaLibraryInfo.registerModule("media3.exoplayer.ima");
    }

    @Nullable
    private AdTagLoader getCurrentAdTagLoader() {
        Object adsId;
        AdTagLoader adTagLoader;
        Player player = this.player;
        if (player == null) {
            return null;
        }
        Timeline currentTimeline = player.getCurrentTimeline();
        if (currentTimeline.isEmpty() || (adsId = currentTimeline.getPeriod(player.getCurrentPeriodIndex(), this.period).getAdsId()) == null || (adTagLoader = this.adTagLoaderByAdsId.get(adsId)) == null || !this.adTagLoaderByAdsMediaSource.containsValue(adTagLoader)) {
            return null;
        }
        return adTagLoader;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void maybePreloadNextPeriodAds() {
        int nextPeriodIndex;
        AdTagLoader adTagLoader;
        Player player = this.player;
        if (player == null) {
            return;
        }
        Timeline currentTimeline = player.getCurrentTimeline();
        if (currentTimeline.isEmpty() || (nextPeriodIndex = currentTimeline.getNextPeriodIndex(player.getCurrentPeriodIndex(), this.period, this.window, player.getRepeatMode(), player.getShuffleModeEnabled())) == -1) {
            return;
        }
        currentTimeline.getPeriod(nextPeriodIndex, this.period);
        Object adsId = this.period.getAdsId();
        if (adsId == null || (adTagLoader = this.adTagLoaderByAdsId.get(adsId)) == null || adTagLoader == this.currentAdTagLoader) {
            return;
        }
        Timeline.Window window = this.window;
        Timeline.Period period = this.period;
        adTagLoader.maybePreloadAds(Util.usToMs(((Long) currentTimeline.getPeriodPositionUs(window, period, period.windowIndex, -9223372036854775807L).second).longValue()), Util.usToMs(this.period.durationUs));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void maybeUpdateCurrentAdTagLoader() {
        AdTagLoader adTagLoader = this.currentAdTagLoader;
        AdTagLoader currentAdTagLoader = getCurrentAdTagLoader();
        if (Objects.equals(adTagLoader, currentAdTagLoader)) {
            return;
        }
        if (adTagLoader != null) {
            adTagLoader.deactivate();
        }
        this.currentAdTagLoader = currentAdTagLoader;
        if (currentAdTagLoader != null) {
            currentAdTagLoader.activate((Player) Assertions.checkNotNull(this.player));
        }
    }

    @UnstableApi
    public void focusSkipButton() {
        AdTagLoader adTagLoader = this.currentAdTagLoader;
        if (adTagLoader != null) {
            adTagLoader.focusSkipButton();
        }
    }

    @Nullable
    @UnstableApi
    public AdDisplayContainer getAdDisplayContainer() {
        AdTagLoader adTagLoader = this.currentAdTagLoader;
        if (adTagLoader != null) {
            return adTagLoader.getAdDisplayContainer();
        }
        return null;
    }

    @Nullable
    @UnstableApi
    public com.google.ads.interactivemedia.v3.api.AdsLoader getAdsLoader() {
        AdTagLoader adTagLoader = this.currentAdTagLoader;
        if (adTagLoader != null) {
            return adTagLoader.getAdsLoader();
        }
        return null;
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    @UnstableApi
    public void handlePrepareComplete(AdsMediaSource adsMediaSource, int i10, int i11) {
        if (this.player == null) {
            return;
        }
        ((AdTagLoader) Assertions.checkNotNull(this.adTagLoaderByAdsMediaSource.get(adsMediaSource))).handlePrepareComplete(i10, i11);
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    @UnstableApi
    public void handlePrepareError(AdsMediaSource adsMediaSource, int i10, int i11, IOException iOException) {
        if (this.player == null) {
            return;
        }
        ((AdTagLoader) Assertions.checkNotNull(this.adTagLoaderByAdsMediaSource.get(adsMediaSource))).handlePrepareError(i10, i11, iOException);
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void release() {
        Player player = this.player;
        if (player != null) {
            player.removeListener(this.playerListener);
            this.player = null;
            maybeUpdateCurrentAdTagLoader();
        }
        this.nextPlayer = null;
        Iterator<AdTagLoader> it = this.adTagLoaderByAdsMediaSource.values().iterator();
        while (it.hasNext()) {
            it.next().release();
        }
        this.adTagLoaderByAdsMediaSource.clear();
        Iterator<AdTagLoader> it2 = this.adTagLoaderByAdsId.values().iterator();
        while (it2.hasNext()) {
            it2.next().release();
        }
        this.adTagLoaderByAdsId.clear();
    }

    @UnstableApi
    public void requestAds(DataSpec dataSpec, Object obj, @Nullable ViewGroup viewGroup) {
        if (this.adTagLoaderByAdsId.containsKey(obj)) {
            return;
        }
        this.adTagLoaderByAdsId.put(obj, new AdTagLoader(this.context, this.configuration, this.imaFactory, this.supportedMimeTypes, dataSpec, obj, viewGroup));
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void setPlayer(@Nullable Player player) {
        Assertions.checkState(Looper.myLooper() == ImaUtil.getImaLooper());
        Assertions.checkState(player == null || player.getApplicationLooper() == ImaUtil.getImaLooper());
        this.nextPlayer = player;
        this.wasSetPlayerCalled = true;
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    @UnstableApi
    public void setSupportedContentTypes(int... iArr) {
        ArrayList arrayList = new ArrayList();
        for (int i10 : iArr) {
            if (i10 == 0) {
                arrayList.add(MimeTypes.APPLICATION_MPD);
            } else if (i10 == 2) {
                arrayList.add(MimeTypes.APPLICATION_M3U8);
            } else if (i10 == 4) {
                arrayList.addAll(Arrays.asList(MimeTypes.VIDEO_MP4, MimeTypes.VIDEO_WEBM, MimeTypes.VIDEO_H263, MimeTypes.AUDIO_MP4, MimeTypes.AUDIO_MPEG));
            }
        }
        this.supportedMimeTypes = Collections.unmodifiableList(arrayList);
    }

    @UnstableApi
    public void skipAd() {
        AdTagLoader adTagLoader = this.currentAdTagLoader;
        if (adTagLoader != null) {
            adTagLoader.skipAd();
        }
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    @UnstableApi
    public void start(AdsMediaSource adsMediaSource, DataSpec dataSpec, Object obj, AdViewProvider adViewProvider, AdsLoader.EventListener eventListener) {
        Assertions.checkState(this.wasSetPlayerCalled, "Set player using adsLoader.setPlayer before preparing the player.");
        if (this.adTagLoaderByAdsMediaSource.isEmpty()) {
            Player player = this.nextPlayer;
            this.player = player;
            if (player == null) {
                return;
            } else {
                player.addListener(this.playerListener);
            }
        }
        AdTagLoader adTagLoader = this.adTagLoaderByAdsId.get(obj);
        if (adTagLoader == null) {
            requestAds(dataSpec, obj, adViewProvider.getAdViewGroup());
            adTagLoader = this.adTagLoaderByAdsId.get(obj);
        }
        this.adTagLoaderByAdsMediaSource.put(adsMediaSource, (AdTagLoader) Assertions.checkNotNull(adTagLoader));
        adTagLoader.addListenerWithAdView(eventListener, adViewProvider);
        maybeUpdateCurrentAdTagLoader();
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    @UnstableApi
    public void stop(AdsMediaSource adsMediaSource, AdsLoader.EventListener eventListener) {
        AdTagLoader adTagLoaderRemove = this.adTagLoaderByAdsMediaSource.remove(adsMediaSource);
        maybeUpdateCurrentAdTagLoader();
        if (adTagLoaderRemove != null) {
            adTagLoaderRemove.removeListener(eventListener);
        }
        if (this.player == null || !this.adTagLoaderByAdsMediaSource.isEmpty()) {
            return;
        }
        this.player.removeListener(this.playerListener);
        this.player = null;
    }

    private ImaAdsLoader(Context context, ImaUtil.Configuration configuration, ImaUtil.ImaFactory imaFactory) {
        this.context = context.getApplicationContext();
        this.configuration = configuration;
        this.imaFactory = imaFactory;
        this.playerListener = new PlayerListenerImpl();
        this.supportedMimeTypes = ImmutableList.t();
        this.adTagLoaderByAdsId = new HashMap<>();
        this.adTagLoaderByAdsMediaSource = new HashMap<>();
        this.period = new Timeline.Period();
        this.window = new Timeline.Window();
    }
}
