package androidx.media3.exoplayer.ima;

import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.media3.common.AdOverlayInfo;
import androidx.media3.common.AdPlaybackState;
import androidx.media3.common.AdViewProvider;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.Timeline;
import androidx.media3.common.util.Assertions;
import androidx.media3.common.util.Log;
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.AdError;
import com.google.ads.interactivemedia.v3.api.AdErrorEvent;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.google.ads.interactivemedia.v3.api.AdPodInfo;
import com.google.ads.interactivemedia.v3.api.AdsLoader;
import com.google.ads.interactivemedia.v3.api.AdsManager;
import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent;
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.ImaSdkSettings;
import com.google.ads.interactivemedia.v3.api.UiElement;
import com.google.ads.interactivemedia.v3.api.player.AdMediaInfo;
import com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider;
import com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer;
import com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.v;
import defpackage.e;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/* JADX INFO: loaded from: classes.dex */
final class AdTagLoader implements Player.Listener {
    private static final int AD_PROGRESS_UPDATE_INTERVAL_MS = 200;
    private static final int IMA_AD_STATE_NONE = 0;
    private static final int IMA_AD_STATE_PAUSED = 2;
    private static final int IMA_AD_STATE_PLAYING = 1;
    private static final long IMA_DURATION_UNSET = -1;
    private static final String IMA_SDK_SETTINGS_PLAYER_TYPE = "google/exo.ext.ima";
    private static final String IMA_SDK_SETTINGS_PLAYER_VERSION = "1.8.0";
    private static final String TAG = "AdTagLoader";
    private static final long THRESHOLD_AD_MATCH_US = 1000;
    private static final long THRESHOLD_END_OF_CONTENT_MS = 5000;
    private final List<VideoAdPlayer.VideoAdPlayerCallback> adCallbacks;
    private final AdDisplayContainer adDisplayContainer;
    private final v adInfoByAdMediaInfo;
    private final Runnable adLoadTimeoutRunnable;
    private AdPlaybackState adPlaybackState;
    private final DataSpec adTagDataSpec;
    private final Object adsId;
    private final AdsLoader adsLoader;

    @Nullable
    private AdsManager adsManager;
    private boolean bufferingAd;
    private final ComponentListener componentListener;
    private final ImaUtil.Configuration configuration;
    private long contentDurationMs;
    private final ContentPlaybackAdapter contentPlaybackAdapter;
    private final List<AdsLoader.EventListener> eventListeners;
    private long fakeContentProgressElapsedRealtimeMs;
    private long fakeContentProgressOffsetMs;
    private final Handler handler;

    @Nullable
    private AdInfo imaAdInfo;

    @Nullable
    private AdMediaInfo imaAdMediaInfo;
    private int imaAdState;
    private final ImaUtil.ImaFactory imaFactory;
    private boolean imaPausedContent;
    private boolean isAdsManagerInitialized;
    private VideoProgressUpdate lastAdProgress;
    private VideoProgressUpdate lastContentProgress;
    private int lastVolumePercent;

    @Nullable
    private AdsMediaSource.AdLoadException pendingAdLoadError;

    @Nullable
    private String pendingAdMimeType;

    @Nullable
    private AdInfo pendingAdPrepareErrorAdInfo;

    @Nullable
    private Object pendingAdRequestContext;
    private long pendingContentPositionMs;
    private final Timeline.Period period;

    @Nullable
    private Player player;
    private boolean playingAd;
    private int playingAdIndexInAdGroup;
    private boolean released;
    private boolean sentContentComplete;
    private boolean sentPendingContentPositionMs;
    private final List<String> supportedMimeTypes;
    private Timeline timeline;
    private final Runnable updateAdProgressRunnable;
    private long waitingForPreloadElapsedRealtimeMs;

    /* JADX INFO: renamed from: androidx.media3.exoplayer.ima.AdTagLoader$1, reason: invalid class name */
    public static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType;

        static {
            int[] iArr = new int[AdEvent.AdEventType.values().length];
            $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType = iArr;
            try {
                iArr[AdEvent.AdEventType.AD_BREAK_FETCH_ERROR.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.CONTENT_PAUSE_REQUESTED.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.TAPPED.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.CLICKED.ordinal()] = 4;
            } catch (NoSuchFieldError unused4) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.CONTENT_RESUME_REQUESTED.ordinal()] = 5;
            } catch (NoSuchFieldError unused5) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.LOG.ordinal()] = 6;
            } catch (NoSuchFieldError unused6) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.LOADED.ordinal()] = 7;
            } catch (NoSuchFieldError unused7) {
            }
        }
    }

    public static final class AdInfo {
        public final int adGroupIndex;
        public final int adIndexInAdGroup;

        public AdInfo(int i10, int i11) {
            this.adGroupIndex = i10;
            this.adIndexInAdGroup = i11;
        }

        public boolean equals(@Nullable Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null || AdInfo.class != obj.getClass()) {
                return false;
            }
            AdInfo adInfo = (AdInfo) obj;
            return this.adGroupIndex == adInfo.adGroupIndex && this.adIndexInAdGroup == adInfo.adIndexInAdGroup;
        }

        public int hashCode() {
            return (this.adGroupIndex * 31) + this.adIndexInAdGroup;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder("(");
            sb.append(this.adGroupIndex);
            sb.append(", ");
            return e.l(sb, this.adIndexInAdGroup, ')');
        }
    }

    public final class ComponentListener implements AdsLoader.AdsLoadedListener, AdEvent.AdEventListener, AdErrorEvent.AdErrorListener {
        private ComponentListener() {
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdErrorEvent.AdErrorListener
        public void onAdError(AdErrorEvent adErrorEvent) {
            AdError error = adErrorEvent.getError();
            if (AdTagLoader.this.configuration.debugModeEnabled) {
                Log.d(AdTagLoader.TAG, "onAdError", error);
            }
            if (AdTagLoader.this.adsManager == null) {
                AdTagLoader.this.pendingAdRequestContext = null;
                AdTagLoader.this.adPlaybackState = new AdPlaybackState(AdTagLoader.this.adsId, new long[0]);
                AdTagLoader.this.updateAdPlaybackState();
            } else if (ImaUtil.isAdGroupLoadError(error)) {
                try {
                    AdTagLoader.this.handleAdGroupLoadError(error);
                } catch (RuntimeException e10) {
                    AdTagLoader.this.maybeNotifyInternalError("onAdError", e10);
                }
            }
            if (AdTagLoader.this.pendingAdLoadError == null) {
                AdTagLoader.this.pendingAdLoadError = AdsMediaSource.AdLoadException.createForAllAds(error);
            }
            AdTagLoader.this.maybeNotifyPendingAdLoadError();
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener
        public void onAdEvent(AdEvent adEvent) {
            AdEvent.AdEventType type = adEvent.getType();
            if (AdTagLoader.this.configuration.debugModeEnabled && type != AdEvent.AdEventType.AD_PROGRESS) {
                Log.d(AdTagLoader.TAG, "onAdEvent: " + type);
            }
            try {
                AdTagLoader.this.handleAdEvent(adEvent);
            } catch (RuntimeException e10) {
                AdTagLoader.this.maybeNotifyInternalError("onAdEvent", e10);
            }
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdsLoader.AdsLoadedListener
        public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) {
            AdsManager adsManager = adsManagerLoadedEvent.getAdsManager();
            if (!Objects.equals(AdTagLoader.this.pendingAdRequestContext, adsManagerLoadedEvent.getUserRequestContext())) {
                adsManager.destroy();
                return;
            }
            AdTagLoader.this.pendingAdRequestContext = null;
            AdTagLoader.this.adsManager = adsManager;
            adsManager.addAdErrorListener(this);
            if (AdTagLoader.this.configuration.applicationAdErrorListener != null) {
                adsManager.addAdErrorListener(AdTagLoader.this.configuration.applicationAdErrorListener);
            }
            adsManager.addAdEventListener(this);
            if (AdTagLoader.this.configuration.applicationAdEventListener != null) {
                adsManager.addAdEventListener(AdTagLoader.this.configuration.applicationAdEventListener);
            }
            try {
                AdTagLoader.this.adPlaybackState = new AdPlaybackState(AdTagLoader.this.adsId, ImaUtil.getAdGroupTimesUsForCuePoints(adsManager.getAdCuePoints()));
                AdTagLoader.this.updateAdPlaybackState();
            } catch (RuntimeException e10) {
                AdTagLoader.this.maybeNotifyInternalError("onAdsManagerLoaded", e10);
            }
        }

        public /* synthetic */ ComponentListener(AdTagLoader adTagLoader, AnonymousClass1 anonymousClass1) {
            this();
        }
    }

    public final class ContentPlaybackAdapter implements ContentProgressProvider {
        private ContentPlaybackAdapter() {
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider
        public VideoProgressUpdate getContentProgress() {
            VideoProgressUpdate contentVideoProgressUpdate = AdTagLoader.this.getContentVideoProgressUpdate();
            if (AdTagLoader.this.configuration.debugModeEnabled) {
                Log.d(AdTagLoader.TAG, "Content progress: " + ImaUtil.getStringForVideoProgressUpdate(contentVideoProgressUpdate));
            }
            if (AdTagLoader.this.waitingForPreloadElapsedRealtimeMs != -9223372036854775807L) {
                if (SystemClock.elapsedRealtime() - AdTagLoader.this.waitingForPreloadElapsedRealtimeMs >= AdTagLoader.this.configuration.adPreloadTimeoutMs) {
                    AdTagLoader.this.waitingForPreloadElapsedRealtimeMs = -9223372036854775807L;
                    AdTagLoader.this.handleAdGroupLoadError(new IOException("Ad preloading timed out"));
                    AdTagLoader.this.maybeNotifyPendingAdLoadError();
                }
            } else if (AdTagLoader.this.pendingContentPositionMs != -9223372036854775807L && AdTagLoader.this.player != null && AdTagLoader.this.player.getPlaybackState() == 2 && AdTagLoader.this.isWaitingForFirstAdToPreload()) {
                AdTagLoader.this.waitingForPreloadElapsedRealtimeMs = SystemClock.elapsedRealtime();
            }
            return contentVideoProgressUpdate;
        }

        public /* synthetic */ ContentPlaybackAdapter(AdTagLoader adTagLoader, AnonymousClass1 anonymousClass1) {
            this();
        }
    }

    public class VideoAdPlayerImpl implements VideoAdPlayer {
        public VideoAdPlayerImpl() {
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer
        public void addCallback(VideoAdPlayer.VideoAdPlayerCallback videoAdPlayerCallback) {
            AdTagLoader.this.adCallbacks.add(videoAdPlayerCallback);
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.AdProgressProvider
        public VideoProgressUpdate getAdProgress() {
            throw new IllegalStateException("Unexpected call to getAdProgress when using preloading");
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VolumeProvider
        public int getVolume() {
            return AdTagLoader.this.getPlayerVolumePercent();
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer
        public void loadAd(AdMediaInfo adMediaInfo, AdPodInfo adPodInfo) {
            try {
                AdTagLoader.this.loadAdInternal(adMediaInfo, adPodInfo);
            } catch (RuntimeException e10) {
                AdTagLoader.this.maybeNotifyInternalError("loadAd", e10);
            }
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer
        public void pauseAd(AdMediaInfo adMediaInfo) {
            try {
                AdTagLoader.this.pauseAdInternal(adMediaInfo);
            } catch (RuntimeException e10) {
                AdTagLoader.this.maybeNotifyInternalError("pauseAd", e10);
            }
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer
        public void playAd(AdMediaInfo adMediaInfo) {
            try {
                AdTagLoader.this.playAdInternal(adMediaInfo);
            } catch (RuntimeException e10) {
                AdTagLoader.this.maybeNotifyInternalError("playAd", e10);
            }
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer
        public void release() {
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer
        public void removeCallback(VideoAdPlayer.VideoAdPlayerCallback videoAdPlayerCallback) {
            AdTagLoader.this.adCallbacks.remove(videoAdPlayerCallback);
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer
        public void stopAd(AdMediaInfo adMediaInfo) {
            try {
                AdTagLoader.this.stopAdInternal(adMediaInfo);
            } catch (RuntimeException e10) {
                AdTagLoader.this.maybeNotifyInternalError("stopAd", e10);
            }
        }
    }

    public AdTagLoader(Context context, ImaUtil.Configuration configuration, ImaUtil.ImaFactory imaFactory, List<String> list, DataSpec dataSpec, Object obj, @Nullable ViewGroup viewGroup) {
        this.configuration = configuration;
        this.imaFactory = imaFactory;
        ImaSdkSettings imaSdkSettingsCreateImaSdkSettings = configuration.imaSdkSettings;
        final int i10 = 1;
        if (imaSdkSettingsCreateImaSdkSettings == null) {
            imaSdkSettingsCreateImaSdkSettings = imaFactory.createImaSdkSettings();
            if (configuration.debugModeEnabled) {
                imaSdkSettingsCreateImaSdkSettings.setDebugMode(true);
            }
        }
        imaSdkSettingsCreateImaSdkSettings.setPlayerType(IMA_SDK_SETTINGS_PLAYER_TYPE);
        imaSdkSettingsCreateImaSdkSettings.setPlayerVersion("1.8.0");
        this.supportedMimeTypes = list;
        this.adTagDataSpec = dataSpec;
        this.adsId = obj;
        this.period = new Timeline.Period();
        AnonymousClass1 anonymousClass1 = null;
        this.handler = Util.createHandler(ImaUtil.getImaLooper(), null);
        this.componentListener = new ComponentListener(this, anonymousClass1);
        this.contentPlaybackAdapter = new ContentPlaybackAdapter(this, anonymousClass1);
        this.eventListeners = new ArrayList();
        ArrayList arrayList = new ArrayList(1);
        this.adCallbacks = arrayList;
        VideoAdPlayer.VideoAdPlayerCallback videoAdPlayerCallback = configuration.applicationVideoAdPlayerCallback;
        if (videoAdPlayerCallback != null) {
            arrayList.add(videoAdPlayerCallback);
        }
        final int i11 = 0;
        this.updateAdProgressRunnable = new Runnable(this) { // from class: androidx.media3.exoplayer.ima.b

            /* JADX INFO: renamed from: b, reason: collision with root package name */
            public final /* synthetic */ AdTagLoader f3061b;

            {
                this.f3061b = this;
            }

            @Override // java.lang.Runnable
            public final void run() {
                int i12 = i11;
                AdTagLoader adTagLoader = this.f3061b;
                switch (i12) {
                    case 0:
                        adTagLoader.updateAdProgress();
                        break;
                    default:
                        adTagLoader.handleAdLoadTimeout();
                        break;
                }
            }
        };
        this.adInfoByAdMediaInfo = HashBiMap.b();
        VideoProgressUpdate videoProgressUpdate = VideoProgressUpdate.VIDEO_TIME_NOT_READY;
        this.lastContentProgress = videoProgressUpdate;
        this.lastAdProgress = videoProgressUpdate;
        this.fakeContentProgressElapsedRealtimeMs = -9223372036854775807L;
        this.fakeContentProgressOffsetMs = -9223372036854775807L;
        this.pendingContentPositionMs = -9223372036854775807L;
        this.waitingForPreloadElapsedRealtimeMs = -9223372036854775807L;
        this.contentDurationMs = -9223372036854775807L;
        this.timeline = Timeline.EMPTY;
        this.adPlaybackState = AdPlaybackState.NONE;
        this.adLoadTimeoutRunnable = new Runnable(this) { // from class: androidx.media3.exoplayer.ima.b

            /* JADX INFO: renamed from: b, reason: collision with root package name */
            public final /* synthetic */ AdTagLoader f3061b;

            {
                this.f3061b = this;
            }

            @Override // java.lang.Runnable
            public final void run() {
                int i12 = i10;
                AdTagLoader adTagLoader = this.f3061b;
                switch (i12) {
                    case 0:
                        adTagLoader.updateAdProgress();
                        break;
                    default:
                        adTagLoader.handleAdLoadTimeout();
                        break;
                }
            }
        };
        VideoAdPlayerImpl videoAdPlayerImpl = new VideoAdPlayerImpl();
        if (viewGroup != null) {
            this.adDisplayContainer = imaFactory.createAdDisplayContainer(viewGroup, videoAdPlayerImpl);
        } else {
            this.adDisplayContainer = imaFactory.createAudioAdDisplayContainer(context, videoAdPlayerImpl);
        }
        Collection<CompanionAdSlot> collection = configuration.companionAdSlots;
        if (collection != null) {
            this.adDisplayContainer.setCompanionSlots(collection);
        }
        this.adsLoader = requestAds(context, imaSdkSettingsCreateImaSdkSettings, this.adDisplayContainer);
    }

    private void destroyAdsManager() {
        AdsManager adsManager = this.adsManager;
        if (adsManager != null) {
            adsManager.removeAdErrorListener(this.componentListener);
            AdErrorEvent.AdErrorListener adErrorListener = this.configuration.applicationAdErrorListener;
            if (adErrorListener != null) {
                this.adsManager.removeAdErrorListener(adErrorListener);
            }
            this.adsManager.removeAdEventListener(this.componentListener);
            AdEvent.AdEventListener adEventListener = this.configuration.applicationAdEventListener;
            if (adEventListener != null) {
                this.adsManager.removeAdEventListener(adEventListener);
            }
            this.adsManager.destroy();
            this.adsManager = null;
        }
    }

    private void ensureSentContentCompleteIfAtEndOfStream() {
        if (this.sentContentComplete || this.contentDurationMs == -9223372036854775807L || this.pendingContentPositionMs != -9223372036854775807L) {
            return;
        }
        long contentPeriodPositionMs = getContentPeriodPositionMs((Player) Assertions.checkNotNull(this.player), this.timeline, this.period);
        if (5000 + contentPeriodPositionMs < this.contentDurationMs) {
            return;
        }
        int adGroupIndexForPositionUs = this.adPlaybackState.getAdGroupIndexForPositionUs(Util.msToUs(contentPeriodPositionMs), Util.msToUs(this.contentDurationMs));
        if (adGroupIndexForPositionUs == -1 || this.adPlaybackState.getAdGroup(adGroupIndexForPositionUs).timeUs == Long.MIN_VALUE || !this.adPlaybackState.getAdGroup(adGroupIndexForPositionUs).shouldPlayAdGroup()) {
            sendContentComplete();
        }
    }

    private int getAdGroupIndexForAdPod(AdPodInfo adPodInfo) {
        return adPodInfo.getPodIndex() == -1 ? this.adPlaybackState.adGroupCount - 1 : getAdGroupIndexForCuePointTimeSeconds(adPodInfo.getTimeOffset());
    }

    private int getAdGroupIndexForCuePointTimeSeconds(double d10) {
        long jRound = Math.round(((double) ((float) d10)) * 1000000.0d);
        int i10 = 0;
        while (true) {
            AdPlaybackState adPlaybackState = this.adPlaybackState;
            if (i10 >= adPlaybackState.adGroupCount) {
                throw new IllegalStateException("Failed to find cue point");
            }
            long j10 = adPlaybackState.getAdGroup(i10).timeUs;
            if (j10 != Long.MIN_VALUE && Math.abs(j10 - jRound) < 1000) {
                return i10;
            }
            i10++;
        }
    }

    private String getAdMediaInfoString(@Nullable AdMediaInfo adMediaInfo) {
        AdInfo adInfo = (AdInfo) this.adInfoByAdMediaInfo.get(adMediaInfo);
        StringBuilder sb = new StringBuilder("AdMediaInfo[");
        sb.append(adMediaInfo == null ? "null" : adMediaInfo.getUrl());
        sb.append(", ");
        sb.append(adInfo);
        sb.append("]");
        return sb.toString();
    }

    private VideoProgressUpdate getAdVideoProgressUpdate() {
        Player player = this.player;
        if (player == null) {
            return this.lastAdProgress;
        }
        if (this.imaAdState == 0 || !this.playingAd) {
            return VideoProgressUpdate.VIDEO_TIME_NOT_READY;
        }
        long duration = player.getDuration();
        return duration == -9223372036854775807L ? VideoProgressUpdate.VIDEO_TIME_NOT_READY : new VideoProgressUpdate(this.player.getCurrentPosition(), duration);
    }

    private static long getContentPeriodPositionMs(Player player, Timeline timeline, Timeline.Period period) {
        long contentPosition = player.getContentPosition();
        return timeline.isEmpty() ? contentPosition : contentPosition - timeline.getPeriod(player.getCurrentPeriodIndex(), period).getPositionInWindowMs();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public VideoProgressUpdate getContentVideoProgressUpdate() {
        boolean z10 = this.contentDurationMs != -9223372036854775807L;
        long contentPeriodPositionMs = this.pendingContentPositionMs;
        if (contentPeriodPositionMs != -9223372036854775807L) {
            this.sentPendingContentPositionMs = true;
        } else {
            Player player = this.player;
            if (player == null) {
                return this.lastContentProgress;
            }
            if (this.fakeContentProgressElapsedRealtimeMs != -9223372036854775807L) {
                contentPeriodPositionMs = this.fakeContentProgressOffsetMs + (SystemClock.elapsedRealtime() - this.fakeContentProgressElapsedRealtimeMs);
            } else {
                if (this.imaAdState != 0 || this.playingAd || !z10) {
                    return VideoProgressUpdate.VIDEO_TIME_NOT_READY;
                }
                contentPeriodPositionMs = getContentPeriodPositionMs(player, this.timeline, this.period);
            }
        }
        return new VideoProgressUpdate(contentPeriodPositionMs, z10 ? this.contentDurationMs : -1L);
    }

    private int getLoadingAdGroupIndex() {
        Player player = this.player;
        if (player == null) {
            return -1;
        }
        long jMsToUs = Util.msToUs(getContentPeriodPositionMs(player, this.timeline, this.period));
        int adGroupIndexForPositionUs = this.adPlaybackState.getAdGroupIndexForPositionUs(jMsToUs, Util.msToUs(this.contentDurationMs));
        return adGroupIndexForPositionUs == -1 ? this.adPlaybackState.getAdGroupIndexAfterPositionUs(jMsToUs, Util.msToUs(this.contentDurationMs)) : adGroupIndexForPositionUs;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public int getPlayerVolumePercent() {
        Player player = this.player;
        return player == null ? this.lastVolumePercent : player.isCommandAvailable(22) ? (int) (player.getVolume() * 100.0f) : player.getCurrentTracks().isTypeSelected(1) ? 100 : 0;
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* JADX WARN: Can't fix incorrect switch cases order, some code will duplicate */
    public void handleAdEvent(AdEvent adEvent) {
        if (this.adsManager == null) {
        }
        int i10 = 0;
        switch (AnonymousClass1.$SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[adEvent.getType().ordinal()]) {
            case 1:
                String str = (String) Assertions.checkNotNull(adEvent.getAdData().get("adBreakTime"));
                if (this.configuration.debugModeEnabled) {
                    Log.d(TAG, "Fetch error for ad at " + str + " seconds");
                }
                double d10 = Double.parseDouble(str);
                markAdGroupInErrorStateAndClearPendingContentPosition(d10 == -1.0d ? this.adPlaybackState.adGroupCount - 1 : getAdGroupIndexForCuePointTimeSeconds(d10));
                break;
            case 2:
                this.imaPausedContent = true;
                pauseContentInternal();
                break;
            case 3:
                while (i10 < this.eventListeners.size()) {
                    this.eventListeners.get(i10).onAdTapped();
                    i10++;
                }
                break;
            case 4:
                while (i10 < this.eventListeners.size()) {
                    this.eventListeners.get(i10).onAdClicked();
                    i10++;
                }
                break;
            case 5:
                this.imaPausedContent = false;
                resumeContentInternal();
                break;
            case 6:
                Log.i(TAG, "AdEvent: " + adEvent.getAdData());
                break;
            case 7:
                this.pendingAdMimeType = adEvent.getAd().getContentType();
                break;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void handleAdGroupLoadError(Exception exc) {
        int loadingAdGroupIndex = getLoadingAdGroupIndex();
        if (loadingAdGroupIndex == -1) {
            Log.w(TAG, "Unable to determine ad group index for ad group load error", exc);
            return;
        }
        markAdGroupInErrorStateAndClearPendingContentPosition(loadingAdGroupIndex);
        if (this.pendingAdLoadError == null) {
            this.pendingAdLoadError = AdsMediaSource.AdLoadException.createForAdGroup(exc, loadingAdGroupIndex);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void handleAdLoadTimeout() {
        if (isWaitingForCurrentAdToLoad()) {
            handleAdGroupLoadError(new IOException("Ad loading timed out"));
            maybeNotifyPendingAdLoadError();
        }
    }

    private void handleAdPrepareError(int i10, int i11, Exception exc) {
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, e.f("Prepare error for ad ", i11, " in group ", i10), exc);
        }
        if (this.adsManager == null) {
            Log.w(TAG, "Ignoring ad prepare error after release");
            return;
        }
        if (this.imaAdState == 0) {
            this.fakeContentProgressElapsedRealtimeMs = SystemClock.elapsedRealtime();
            long jUsToMs = Util.usToMs(this.adPlaybackState.getAdGroup(i10).timeUs);
            this.fakeContentProgressOffsetMs = jUsToMs;
            if (jUsToMs == Long.MIN_VALUE) {
                this.fakeContentProgressOffsetMs = this.contentDurationMs;
            }
            this.pendingAdPrepareErrorAdInfo = new AdInfo(i10, i11);
        } else {
            AdMediaInfo adMediaInfo = (AdMediaInfo) Assertions.checkNotNull(this.imaAdMediaInfo);
            if (i11 > this.playingAdIndexInAdGroup) {
                for (int i12 = 0; i12 < this.adCallbacks.size(); i12++) {
                    this.adCallbacks.get(i12).onEnded(adMediaInfo);
                }
            }
            this.playingAdIndexInAdGroup = this.adPlaybackState.getAdGroup(i10).getFirstAdIndexToPlay();
            for (int i13 = 0; i13 < this.adCallbacks.size(); i13++) {
                this.adCallbacks.get(i13).onError((AdMediaInfo) Assertions.checkNotNull(adMediaInfo));
            }
        }
        this.adPlaybackState = this.adPlaybackState.withAdLoadError(i10, i11);
        updateAdPlaybackState();
    }

    private void handlePlayerStateChanged(boolean z10, int i10) {
        if (this.playingAd && this.imaAdState == 1) {
            boolean z11 = this.bufferingAd;
            if (!z11 && i10 == 2) {
                this.bufferingAd = true;
                AdMediaInfo adMediaInfo = (AdMediaInfo) Assertions.checkNotNull(this.imaAdMediaInfo);
                for (int i11 = 0; i11 < this.adCallbacks.size(); i11++) {
                    this.adCallbacks.get(i11).onBuffering(adMediaInfo);
                }
                stopUpdatingAdProgress();
            } else if (z11 && i10 == 3) {
                this.bufferingAd = false;
                updateAdProgress();
            }
        }
        int i12 = this.imaAdState;
        if (i12 == 0 && ((i10 == 2 || i10 == 4) && z10)) {
            ensureSentContentCompleteIfAtEndOfStream();
            return;
        }
        if (i12 == 0 || i10 != 4) {
            return;
        }
        AdMediaInfo adMediaInfo2 = this.imaAdMediaInfo;
        if (adMediaInfo2 == null) {
            Log.w(TAG, "onEnded without ad media info");
        } else {
            for (int i13 = 0; i13 < this.adCallbacks.size(); i13++) {
                this.adCallbacks.get(i13).onEnded(adMediaInfo2);
            }
        }
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "VideoAdPlayerCallback.onEnded in onPlaybackStateChanged");
        }
    }

    private void handleTimelineOrPositionChanged() {
        Player player = this.player;
        if (this.adsManager == null || player == null) {
            return;
        }
        if (!this.playingAd && !player.isPlayingAd()) {
            ensureSentContentCompleteIfAtEndOfStream();
            if (!this.sentContentComplete && !this.timeline.isEmpty()) {
                long contentPeriodPositionMs = getContentPeriodPositionMs(player, this.timeline, this.period);
                this.timeline.getPeriod(player.getCurrentPeriodIndex(), this.period);
                if (this.period.getAdGroupIndexForPositionUs(Util.msToUs(contentPeriodPositionMs)) != -1) {
                    this.sentPendingContentPositionMs = false;
                    this.pendingContentPositionMs = contentPeriodPositionMs;
                }
            }
        }
        boolean z10 = this.playingAd;
        int i10 = this.playingAdIndexInAdGroup;
        boolean zIsPlayingAd = player.isPlayingAd();
        this.playingAd = zIsPlayingAd;
        int currentAdIndexInAdGroup = zIsPlayingAd ? player.getCurrentAdIndexInAdGroup() : -1;
        this.playingAdIndexInAdGroup = currentAdIndexInAdGroup;
        if (z10 && currentAdIndexInAdGroup != i10) {
            AdMediaInfo adMediaInfo = this.imaAdMediaInfo;
            if (adMediaInfo == null) {
                Log.w(TAG, "onEnded without ad media info");
            } else {
                AdInfo adInfo = (AdInfo) this.adInfoByAdMediaInfo.get(adMediaInfo);
                int i11 = this.playingAdIndexInAdGroup;
                if (i11 == -1 || (adInfo != null && adInfo.adIndexInAdGroup < i11)) {
                    for (int i12 = 0; i12 < this.adCallbacks.size(); i12++) {
                        this.adCallbacks.get(i12).onEnded(adMediaInfo);
                    }
                    if (this.configuration.debugModeEnabled) {
                        Log.d(TAG, "VideoAdPlayerCallback.onEnded in onTimelineChanged/onPositionDiscontinuity");
                    }
                }
            }
        }
        if (!this.sentContentComplete && !z10 && this.playingAd && this.imaAdState == 0) {
            AdPlaybackState.AdGroup adGroup = this.adPlaybackState.getAdGroup(player.getCurrentAdGroupIndex());
            if (adGroup.timeUs == Long.MIN_VALUE) {
                sendContentComplete();
            } else {
                this.fakeContentProgressElapsedRealtimeMs = SystemClock.elapsedRealtime();
                long jUsToMs = Util.usToMs(adGroup.timeUs);
                this.fakeContentProgressOffsetMs = jUsToMs;
                if (jUsToMs == Long.MIN_VALUE) {
                    this.fakeContentProgressOffsetMs = this.contentDurationMs;
                }
            }
        }
        if (isWaitingForCurrentAdToLoad()) {
            this.handler.removeCallbacks(this.adLoadTimeoutRunnable);
            this.handler.postDelayed(this.adLoadTimeoutRunnable, this.configuration.adPreloadTimeoutMs);
        }
    }

    private static boolean hasMidrollAdGroups(AdPlaybackState adPlaybackState) {
        int i10 = adPlaybackState.adGroupCount;
        if (i10 == 1) {
            long j10 = adPlaybackState.getAdGroup(0).timeUs;
            return (j10 == 0 || j10 == Long.MIN_VALUE) ? false : true;
        }
        if (i10 == 2) {
            return (adPlaybackState.getAdGroup(0).timeUs == 0 && adPlaybackState.getAdGroup(1).timeUs == Long.MIN_VALUE) ? false : true;
        }
        return true;
    }

    private boolean isWaitingForCurrentAdToLoad() {
        int currentAdGroupIndex;
        Player player = this.player;
        if (player == null || (currentAdGroupIndex = player.getCurrentAdGroupIndex()) == -1) {
            return false;
        }
        AdPlaybackState adPlaybackState = this.adPlaybackState;
        if (currentAdGroupIndex >= adPlaybackState.adGroupCount) {
            return true;
        }
        AdPlaybackState.AdGroup adGroup = adPlaybackState.getAdGroup(currentAdGroupIndex);
        int currentAdIndexInAdGroup = player.getCurrentAdIndexInAdGroup();
        int i10 = adGroup.count;
        return i10 == -1 || i10 <= currentAdIndexInAdGroup || adGroup.states[currentAdIndexInAdGroup] == 0;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public boolean isWaitingForFirstAdToPreload() {
        int loadingAdGroupIndex;
        Player player = this.player;
        if (player == null || (loadingAdGroupIndex = getLoadingAdGroupIndex()) == -1) {
            return false;
        }
        AdPlaybackState.AdGroup adGroup = this.adPlaybackState.getAdGroup(loadingAdGroupIndex);
        int i10 = adGroup.count;
        return (i10 == -1 || i10 == 0 || adGroup.states[0] == 0) && Util.usToMs(adGroup.timeUs) - getContentPeriodPositionMs(player, this.timeline, this.period) < this.configuration.adPreloadTimeoutMs;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$deactivate$0(Player player) {
        player.removeListener(this);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void loadAdInternal(AdMediaInfo adMediaInfo, AdPodInfo adPodInfo) {
        if (this.adsManager == null) {
            if (this.configuration.debugModeEnabled) {
                Log.d(TAG, "loadAd after release " + getAdMediaInfoString(adMediaInfo) + ", ad pod " + adPodInfo);
                return;
            }
            return;
        }
        int adGroupIndexForAdPod = getAdGroupIndexForAdPod(adPodInfo);
        int adPosition = adPodInfo.getAdPosition() - 1;
        AdInfo adInfo = new AdInfo(adGroupIndexForAdPod, adPosition);
        this.adInfoByAdMediaInfo.f(adMediaInfo, adInfo);
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "loadAd " + getAdMediaInfoString(adMediaInfo));
        }
        if (this.adPlaybackState.isAdInErrorState(adGroupIndexForAdPod, adPosition)) {
            return;
        }
        AdPlaybackState adPlaybackStateWithAdCount = this.adPlaybackState.withAdCount(adInfo.adGroupIndex, Math.max(adPodInfo.getTotalAds(), this.adPlaybackState.getAdGroup(adInfo.adGroupIndex).states.length));
        this.adPlaybackState = adPlaybackStateWithAdCount;
        AdPlaybackState.AdGroup adGroup = adPlaybackStateWithAdCount.getAdGroup(adInfo.adGroupIndex);
        for (int i10 = 0; i10 < adPosition; i10++) {
            if (adGroup.states[i10] == 0) {
                this.adPlaybackState = this.adPlaybackState.withAdLoadError(adGroupIndexForAdPod, i10);
            }
        }
        MediaItem.Builder uri = new MediaItem.Builder().setUri(adMediaInfo.getUrl());
        String str = this.pendingAdMimeType;
        if (str != null) {
            uri.setMimeType(str);
            this.pendingAdMimeType = null;
        }
        this.adPlaybackState = this.adPlaybackState.withAvailableAdMediaItem(adInfo.adGroupIndex, adInfo.adIndexInAdGroup, uri.build());
        updateAdPlaybackState();
    }

    private void markAdGroupInErrorStateAndClearPendingContentPosition(int i10) {
        AdPlaybackState.AdGroup adGroup = this.adPlaybackState.getAdGroup(i10);
        if (adGroup.count == -1) {
            AdPlaybackState adPlaybackStateWithAdCount = this.adPlaybackState.withAdCount(i10, Math.max(1, adGroup.states.length));
            this.adPlaybackState = adPlaybackStateWithAdCount;
            adGroup = adPlaybackStateWithAdCount.getAdGroup(i10);
        }
        for (int i11 = 0; i11 < adGroup.count; i11++) {
            if (adGroup.states[i11] == 0) {
                if (this.configuration.debugModeEnabled) {
                    Log.d(TAG, "Removing ad " + i11 + " in ad group " + i10);
                }
                this.adPlaybackState = this.adPlaybackState.withAdLoadError(i10, i11);
            }
        }
        updateAdPlaybackState();
        this.pendingContentPositionMs = -9223372036854775807L;
        this.fakeContentProgressElapsedRealtimeMs = -9223372036854775807L;
    }

    private void maybeInitializeAdsManager(long j10, long j11) {
        AdsManager adsManager = this.adsManager;
        if (this.isAdsManagerInitialized || adsManager == null) {
            return;
        }
        this.isAdsManagerInitialized = true;
        AdsRenderingSettings adsRenderingSettings = setupAdsRendering(j10, j11);
        if (adsRenderingSettings == null) {
            destroyAdsManager();
        } else {
            adsManager.init(adsRenderingSettings);
            adsManager.start();
            if (this.configuration.debugModeEnabled) {
                Log.d(TAG, "Initialized with ads rendering settings: " + adsRenderingSettings);
            }
        }
        updateAdPlaybackState();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void maybeNotifyInternalError(String str, Exception exc) {
        String str2 = "Internal error in " + str;
        Log.e(TAG, str2, exc);
        int i10 = 0;
        while (true) {
            AdPlaybackState adPlaybackState = this.adPlaybackState;
            if (i10 >= adPlaybackState.adGroupCount) {
                break;
            }
            this.adPlaybackState = adPlaybackState.withSkippedAdGroup(i10);
            i10++;
        }
        updateAdPlaybackState();
        for (int i11 = 0; i11 < this.eventListeners.size(); i11++) {
            this.eventListeners.get(i11).onAdLoadError(AdsMediaSource.AdLoadException.createForUnexpected(new RuntimeException(str2, exc)), this.adTagDataSpec);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void maybeNotifyPendingAdLoadError() {
        if (this.pendingAdLoadError != null) {
            for (int i10 = 0; i10 < this.eventListeners.size(); i10++) {
                this.eventListeners.get(i10).onAdLoadError(this.pendingAdLoadError, this.adTagDataSpec);
            }
            this.pendingAdLoadError = null;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void pauseAdInternal(AdMediaInfo adMediaInfo) {
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "pauseAd " + getAdMediaInfoString(adMediaInfo));
        }
        if (this.adsManager == null || this.imaAdState == 0) {
            return;
        }
        if (this.configuration.debugModeEnabled && !adMediaInfo.equals(this.imaAdMediaInfo)) {
            Log.w(TAG, "Unexpected pauseAd for " + getAdMediaInfoString(adMediaInfo) + ", expected " + getAdMediaInfoString(this.imaAdMediaInfo));
        }
        this.imaAdState = 2;
        for (int i10 = 0; i10 < this.adCallbacks.size(); i10++) {
            this.adCallbacks.get(i10).onPause(adMediaInfo);
        }
    }

    private void pauseContentInternal() {
        this.imaAdState = 0;
        if (this.sentPendingContentPositionMs) {
            this.pendingContentPositionMs = -9223372036854775807L;
            this.sentPendingContentPositionMs = false;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void playAdInternal(AdMediaInfo adMediaInfo) {
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "playAd " + getAdMediaInfoString(adMediaInfo));
        }
        if (this.adsManager == null) {
            return;
        }
        if (this.imaAdState == 1) {
            Log.w(TAG, "Unexpected playAd without stopAd");
        }
        int i10 = 0;
        if (this.imaAdState == 0) {
            this.fakeContentProgressElapsedRealtimeMs = -9223372036854775807L;
            this.fakeContentProgressOffsetMs = -9223372036854775807L;
            this.imaAdState = 1;
            this.imaAdMediaInfo = adMediaInfo;
            this.imaAdInfo = (AdInfo) Assertions.checkNotNull((AdInfo) this.adInfoByAdMediaInfo.get(adMediaInfo));
            for (int i11 = 0; i11 < this.adCallbacks.size(); i11++) {
                this.adCallbacks.get(i11).onPlay(adMediaInfo);
            }
            AdInfo adInfo = this.pendingAdPrepareErrorAdInfo;
            if (adInfo != null && adInfo.equals(this.imaAdInfo)) {
                this.pendingAdPrepareErrorAdInfo = null;
                while (i10 < this.adCallbacks.size()) {
                    this.adCallbacks.get(i10).onError(adMediaInfo);
                    i10++;
                }
            }
            updateAdProgress();
        } else {
            this.imaAdState = 1;
            Assertions.checkState(adMediaInfo.equals(this.imaAdMediaInfo));
            while (i10 < this.adCallbacks.size()) {
                this.adCallbacks.get(i10).onResume(adMediaInfo);
                i10++;
            }
        }
        Player player = this.player;
        if (player == null || !player.getPlayWhenReady()) {
            ((AdsManager) Assertions.checkNotNull(this.adsManager)).pause();
        }
    }

    private com.google.ads.interactivemedia.v3.api.AdsLoader requestAds(Context context, ImaSdkSettings imaSdkSettings, AdDisplayContainer adDisplayContainer) {
        com.google.ads.interactivemedia.v3.api.AdsLoader adsLoaderCreateAdsLoader = this.imaFactory.createAdsLoader(context, imaSdkSettings, adDisplayContainer);
        adsLoaderCreateAdsLoader.addAdErrorListener(this.componentListener);
        AdErrorEvent.AdErrorListener adErrorListener = this.configuration.applicationAdErrorListener;
        if (adErrorListener != null) {
            adsLoaderCreateAdsLoader.addAdErrorListener(adErrorListener);
        }
        adsLoaderCreateAdsLoader.addAdsLoadedListener(this.componentListener);
        try {
            AdsRequest adsRequestForAdTagDataSpec = ImaUtil.getAdsRequestForAdTagDataSpec(this.imaFactory, this.adTagDataSpec);
            Object obj = new Object();
            this.pendingAdRequestContext = obj;
            adsRequestForAdTagDataSpec.setUserRequestContext(obj);
            Boolean bool = this.configuration.enableContinuousPlayback;
            if (bool != null) {
                adsRequestForAdTagDataSpec.setContinuousPlayback(bool.booleanValue());
            }
            int i10 = this.configuration.vastLoadTimeoutMs;
            if (i10 != -1) {
                adsRequestForAdTagDataSpec.setVastLoadTimeout(i10);
            }
            adsRequestForAdTagDataSpec.setContentProgressProvider(this.contentPlaybackAdapter);
            adsLoaderCreateAdsLoader.requestAds(adsRequestForAdTagDataSpec);
            return adsLoaderCreateAdsLoader;
        } catch (IOException e10) {
            this.adPlaybackState = new AdPlaybackState(this.adsId, new long[0]);
            updateAdPlaybackState();
            this.pendingAdLoadError = AdsMediaSource.AdLoadException.createForAllAds(e10);
            maybeNotifyPendingAdLoadError();
            return adsLoaderCreateAdsLoader;
        }
    }

    private void resumeContentInternal() {
        AdInfo adInfo = this.imaAdInfo;
        if (adInfo != null) {
            this.adPlaybackState = this.adPlaybackState.withSkippedAdGroup(((AdInfo) Assertions.checkNotNull(adInfo)).adGroupIndex);
            updateAdPlaybackState();
        }
    }

    private void sendContentComplete() {
        int i10 = 0;
        for (int i11 = 0; i11 < this.adCallbacks.size(); i11++) {
            this.adCallbacks.get(i11).onContentComplete();
        }
        this.sentContentComplete = true;
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "adsLoader.contentComplete");
        }
        while (true) {
            AdPlaybackState adPlaybackState = this.adPlaybackState;
            if (i10 >= adPlaybackState.adGroupCount) {
                updateAdPlaybackState();
                return;
            } else {
                if (adPlaybackState.getAdGroup(i10).timeUs != Long.MIN_VALUE) {
                    this.adPlaybackState = this.adPlaybackState.withSkippedAdGroup(i10);
                }
                i10++;
            }
        }
    }

    @Nullable
    private AdsRenderingSettings setupAdsRendering(long j10, long j11) {
        AdsRenderingSettings adsRenderingSettingsCreateAdsRenderingSettings = this.imaFactory.createAdsRenderingSettings();
        adsRenderingSettingsCreateAdsRenderingSettings.setEnablePreloading(true);
        List<String> list = this.configuration.adMediaMimeTypes;
        if (list == null) {
            list = this.supportedMimeTypes;
        }
        adsRenderingSettingsCreateAdsRenderingSettings.setMimeTypes(list);
        int i10 = this.configuration.mediaLoadTimeoutMs;
        if (i10 != -1) {
            adsRenderingSettingsCreateAdsRenderingSettings.setLoadVideoTimeout(i10);
        }
        int i11 = this.configuration.mediaBitrate;
        if (i11 != -1) {
            adsRenderingSettingsCreateAdsRenderingSettings.setBitrateKbps(i11 / 1000);
        }
        adsRenderingSettingsCreateAdsRenderingSettings.setFocusSkipButtonWhenAvailable(this.configuration.focusSkipButtonWhenAvailable);
        Set<UiElement> set = this.configuration.adUiElements;
        if (set != null) {
            adsRenderingSettingsCreateAdsRenderingSettings.setUiElements(set);
        }
        int adGroupIndexForPositionUs = this.adPlaybackState.getAdGroupIndexForPositionUs(Util.msToUs(j10), Util.msToUs(j11));
        if (adGroupIndexForPositionUs != -1) {
            if (this.adPlaybackState.getAdGroup(adGroupIndexForPositionUs).timeUs != Util.msToUs(j10) && !this.configuration.playAdBeforeStartPosition) {
                adGroupIndexForPositionUs++;
            } else if (hasMidrollAdGroups(this.adPlaybackState)) {
                this.pendingContentPositionMs = j10;
            }
            if (adGroupIndexForPositionUs > 0) {
                for (int i12 = 0; i12 < adGroupIndexForPositionUs; i12++) {
                    this.adPlaybackState = this.adPlaybackState.withSkippedAdGroup(i12);
                }
                AdPlaybackState adPlaybackState = this.adPlaybackState;
                if (adGroupIndexForPositionUs == adPlaybackState.adGroupCount) {
                    return null;
                }
                long j12 = adPlaybackState.getAdGroup(adGroupIndexForPositionUs).timeUs;
                long j13 = this.adPlaybackState.getAdGroup(adGroupIndexForPositionUs - 1).timeUs;
                if (j12 == Long.MIN_VALUE) {
                    adsRenderingSettingsCreateAdsRenderingSettings.setPlayAdsAfterTime((j13 / 1000000.0d) + 1.0d);
                } else {
                    adsRenderingSettingsCreateAdsRenderingSettings.setPlayAdsAfterTime(((j12 + j13) / 2.0d) / 1000000.0d);
                }
            }
        }
        return adsRenderingSettingsCreateAdsRenderingSettings;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void stopAdInternal(AdMediaInfo adMediaInfo) {
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "stopAd " + getAdMediaInfoString(adMediaInfo));
        }
        if (this.adsManager == null) {
            return;
        }
        if (this.imaAdState == 0) {
            AdInfo adInfo = (AdInfo) this.adInfoByAdMediaInfo.get(adMediaInfo);
            if (adInfo != null) {
                this.adPlaybackState = this.adPlaybackState.withSkippedAd(adInfo.adGroupIndex, adInfo.adIndexInAdGroup);
                updateAdPlaybackState();
                return;
            }
            return;
        }
        this.imaAdState = 0;
        stopUpdatingAdProgress();
        Assertions.checkNotNull(this.imaAdInfo);
        AdInfo adInfo2 = this.imaAdInfo;
        int i10 = adInfo2.adGroupIndex;
        int i11 = adInfo2.adIndexInAdGroup;
        if (this.adPlaybackState.isAdInErrorState(i10, i11)) {
            return;
        }
        this.adPlaybackState = this.adPlaybackState.withPlayedAd(i10, i11).withAdResumePositionUs(0L);
        updateAdPlaybackState();
        if (this.playingAd) {
            return;
        }
        this.imaAdMediaInfo = null;
        this.imaAdInfo = null;
    }

    private void stopUpdatingAdProgress() {
        this.handler.removeCallbacks(this.updateAdProgressRunnable);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void updateAdPlaybackState() {
        for (int i10 = 0; i10 < this.eventListeners.size(); i10++) {
            this.eventListeners.get(i10).onAdPlaybackState(this.adPlaybackState);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void updateAdProgress() {
        VideoProgressUpdate adVideoProgressUpdate = getAdVideoProgressUpdate();
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "Ad progress: " + ImaUtil.getStringForVideoProgressUpdate(adVideoProgressUpdate));
        }
        AdMediaInfo adMediaInfo = (AdMediaInfo) Assertions.checkNotNull(this.imaAdMediaInfo);
        for (int i10 = 0; i10 < this.adCallbacks.size(); i10++) {
            this.adCallbacks.get(i10).onAdProgress(adMediaInfo, adVideoProgressUpdate);
        }
        this.handler.removeCallbacks(this.updateAdProgressRunnable);
        this.handler.postDelayed(this.updateAdProgressRunnable, 200L);
    }

    public void activate(Player player) {
        AdInfo adInfo;
        this.player = player;
        player.addListener(this);
        boolean playWhenReady = player.getPlayWhenReady();
        onTimelineChanged(player.getCurrentTimeline(), 1);
        AdsManager adsManager = this.adsManager;
        if (AdPlaybackState.NONE.equals(this.adPlaybackState) || adsManager == null || !this.imaPausedContent) {
            return;
        }
        int adGroupIndexForPositionUs = this.adPlaybackState.getAdGroupIndexForPositionUs(Util.msToUs(getContentPeriodPositionMs(player, this.timeline, this.period)), Util.msToUs(this.contentDurationMs));
        if (adGroupIndexForPositionUs != -1 && (adInfo = this.imaAdInfo) != null && adInfo.adGroupIndex != adGroupIndexForPositionUs) {
            if (this.configuration.debugModeEnabled) {
                Log.d(TAG, "Discarding preloaded ad " + this.imaAdInfo);
            }
            adsManager.discardAdBreak();
        }
        if (playWhenReady) {
            adsManager.resume();
        }
    }

    public void addListenerWithAdView(AdsLoader.EventListener eventListener, AdViewProvider adViewProvider) {
        boolean z10 = !this.eventListeners.isEmpty();
        this.eventListeners.add(eventListener);
        if (z10) {
            if (AdPlaybackState.NONE.equals(this.adPlaybackState)) {
                return;
            }
            eventListener.onAdPlaybackState(this.adPlaybackState);
            return;
        }
        this.lastVolumePercent = 0;
        VideoProgressUpdate videoProgressUpdate = VideoProgressUpdate.VIDEO_TIME_NOT_READY;
        this.lastAdProgress = videoProgressUpdate;
        this.lastContentProgress = videoProgressUpdate;
        maybeNotifyPendingAdLoadError();
        if (!AdPlaybackState.NONE.equals(this.adPlaybackState)) {
            eventListener.onAdPlaybackState(this.adPlaybackState);
        } else if (this.adsManager != null) {
            this.adPlaybackState = new AdPlaybackState(this.adsId, ImaUtil.getAdGroupTimesUsForCuePoints(this.adsManager.getAdCuePoints()));
            updateAdPlaybackState();
        }
        for (AdOverlayInfo adOverlayInfo : adViewProvider.getAdOverlayInfos()) {
            this.adDisplayContainer.registerFriendlyObstruction(this.imaFactory.createFriendlyObstruction(adOverlayInfo.view, ImaUtil.getFriendlyObstructionPurpose(adOverlayInfo.purpose), adOverlayInfo.reasonDetail));
        }
    }

    public void deactivate() {
        Player player = (Player) Assertions.checkNotNull(this.player);
        if (!AdPlaybackState.NONE.equals(this.adPlaybackState) && this.imaPausedContent) {
            AdsManager adsManager = this.adsManager;
            if (adsManager != null) {
                adsManager.pause();
            }
            this.adPlaybackState = this.adPlaybackState.withAdResumePositionUs(this.playingAd ? Util.msToUs(player.getCurrentPosition()) : 0L);
        }
        this.lastVolumePercent = getPlayerVolumePercent();
        this.lastAdProgress = getAdVideoProgressUpdate();
        this.lastContentProgress = getContentVideoProgressUpdate();
        this.handler.post(new a(this, player, 0));
        this.player = null;
    }

    public void focusSkipButton() {
        AdsManager adsManager = this.adsManager;
        if (adsManager != null) {
            adsManager.focus();
        }
    }

    public AdDisplayContainer getAdDisplayContainer() {
        return this.adDisplayContainer;
    }

    public com.google.ads.interactivemedia.v3.api.AdsLoader getAdsLoader() {
        return this.adsLoader;
    }

    public void handlePrepareComplete(int i10, int i11) {
        AdInfo adInfo = new AdInfo(i10, i11);
        if (this.configuration.debugModeEnabled) {
            Log.d(TAG, "Prepared ad " + adInfo);
        }
        AdMediaInfo adMediaInfo = (AdMediaInfo) this.adInfoByAdMediaInfo.h().get(adInfo);
        if (adMediaInfo == null) {
            Log.w(TAG, "Unexpected prepared ad " + adInfo);
        } else {
            for (int i12 = 0; i12 < this.adCallbacks.size(); i12++) {
                this.adCallbacks.get(i12).onLoaded(adMediaInfo);
            }
        }
    }

    public void handlePrepareError(int i10, int i11, IOException iOException) {
        if (this.player == null) {
            return;
        }
        try {
            handleAdPrepareError(i10, i11, iOException);
        } catch (RuntimeException e10) {
            maybeNotifyInternalError("handlePrepareError", e10);
        }
    }

    public void maybePreloadAds(long j10, long j11) {
        maybeInitializeAdsManager(j10, j11);
    }

    @Override // androidx.media3.common.Player.Listener
    public void onPlayWhenReadyChanged(boolean z10, int i10) {
        Player player;
        AdsManager adsManager = this.adsManager;
        if (adsManager == null || (player = this.player) == null) {
            return;
        }
        int i11 = this.imaAdState;
        if (i11 == 1 && !z10) {
            adsManager.pause();
        } else if (i11 == 2 && z10) {
            adsManager.resume();
        } else {
            handlePlayerStateChanged(z10, player.getPlaybackState());
        }
    }

    @Override // androidx.media3.common.Player.Listener
    public void onPlaybackStateChanged(int i10) {
        Player player = this.player;
        if (this.adsManager == null || player == null) {
            return;
        }
        if (i10 == 2 && !player.isPlayingAd() && isWaitingForFirstAdToPreload()) {
            this.waitingForPreloadElapsedRealtimeMs = SystemClock.elapsedRealtime();
        } else if (i10 == 3) {
            this.waitingForPreloadElapsedRealtimeMs = -9223372036854775807L;
        }
        handlePlayerStateChanged(player.getPlayWhenReady(), i10);
    }

    @Override // androidx.media3.common.Player.Listener
    public void onPlayerError(PlaybackException playbackException) {
        if (this.imaAdState != 0) {
            AdMediaInfo adMediaInfo = (AdMediaInfo) Assertions.checkNotNull(this.imaAdMediaInfo);
            for (int i10 = 0; i10 < this.adCallbacks.size(); i10++) {
                this.adCallbacks.get(i10).onError(adMediaInfo);
            }
        }
    }

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

    @Override // androidx.media3.common.Player.Listener
    public void onTimelineChanged(Timeline timeline, int i10) {
        Player player;
        if (timeline.isEmpty() || (player = this.player) == null) {
            return;
        }
        this.timeline = timeline;
        long j10 = timeline.getPeriod(player.getCurrentPeriodIndex(), this.period).durationUs;
        this.contentDurationMs = Util.usToMs(j10);
        AdPlaybackState adPlaybackState = this.adPlaybackState;
        if (j10 != adPlaybackState.contentDurationUs) {
            this.adPlaybackState = adPlaybackState.withContentDurationUs(j10);
            updateAdPlaybackState();
        }
        maybeInitializeAdsManager(getContentPeriodPositionMs(player, timeline, this.period), this.contentDurationMs);
        handleTimelineOrPositionChanged();
    }

    public void release() {
        if (this.released) {
            return;
        }
        this.released = true;
        this.pendingAdRequestContext = null;
        destroyAdsManager();
        this.adsLoader.removeAdsLoadedListener(this.componentListener);
        this.adsLoader.removeAdErrorListener(this.componentListener);
        AdErrorEvent.AdErrorListener adErrorListener = this.configuration.applicationAdErrorListener;
        if (adErrorListener != null) {
            this.adsLoader.removeAdErrorListener(adErrorListener);
        }
        this.adsLoader.release();
        int i10 = 0;
        this.imaPausedContent = false;
        this.imaAdState = 0;
        this.imaAdMediaInfo = null;
        stopUpdatingAdProgress();
        this.imaAdInfo = null;
        this.pendingAdLoadError = null;
        while (true) {
            AdPlaybackState adPlaybackState = this.adPlaybackState;
            if (i10 >= adPlaybackState.adGroupCount) {
                updateAdPlaybackState();
                return;
            } else {
                this.adPlaybackState = adPlaybackState.withSkippedAdGroup(i10);
                i10++;
            }
        }
    }

    public void removeListener(AdsLoader.EventListener eventListener) {
        this.eventListeners.remove(eventListener);
        if (this.eventListeners.isEmpty()) {
            this.adDisplayContainer.unregisterAllFriendlyObstructions();
        }
    }

    public void skipAd() {
        AdsManager adsManager = this.adsManager;
        if (adsManager != null) {
            adsManager.skip();
        }
    }
}
