package androidx.media3.exoplayer.hls;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.media3.common.AdPlaybackState;
import androidx.media3.common.AdViewProvider;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Metadata;
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.Consumer;
import androidx.media3.common.util.Log;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DataSpec;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.PlayerMessage;
import androidx.media3.exoplayer.drm.DrmSessionManagerProvider;
import androidx.media3.exoplayer.hls.HlsInterstitialsAdsLoader;
import androidx.media3.exoplayer.hls.HlsMediaSource;
import androidx.media3.exoplayer.hls.playlist.HlsMediaPlaylist;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.ads.AdsLoader;
import androidx.media3.exoplayer.source.ads.AdsMediaSource;
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy;
import androidx.media3.exoplayer.upstream.Loader;
import androidx.media3.exoplayer.upstream.ParsingLoadable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.m0;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;

/* JADX INFO: loaded from: classes.dex */
@UnstableApi
public final class HlsInterstitialsAdsLoader implements AdsLoader {
    private static final String TAG = "HlsInterstitiaAdsLoader";
    private final Map<Object, AdPlaybackState> activeAdPlaybackStates;
    private final Map<Object, AdsLoader.EventListener> activeEventListeners;
    private final DataSource.Factory dataSourceFactory;
    private final Map<Object, Set<String>> insertedInterstitialIds;
    private boolean isReleased;
    private final List<Listener> listeners;

    @Nullable
    private Loader loader;

    @Nullable
    private PlayerMessage pendingAssetListResolutionMessage;

    @Nullable
    private ExoPlayer player;
    private final PlayerListener playerListener;
    private final Map<Object, AdPlaybackState> resumptionStates;
    private final Map<Object, TreeMap<Long, AssetListData>> unresolvedAssetLists;
    private final Set<Object> unsupportedAdsIds;

    public static final class AdsMediaSourceFactory implements MediaSource.Factory {
        private final AdViewProvider adViewProvider;
        private final HlsInterstitialsAdsLoader adsLoader;
        private final MediaSource.Factory mediaSourceFactory;

        public AdsMediaSourceFactory(HlsInterstitialsAdsLoader hlsInterstitialsAdsLoader, AdViewProvider adViewProvider, Context context) {
            this(hlsInterstitialsAdsLoader, context, null, adViewProvider);
        }

        @Override // androidx.media3.exoplayer.source.MediaSource.Factory
        public MediaSource createMediaSource(MediaItem mediaItem) {
            Assertions.checkNotNull(mediaItem.localConfiguration);
            MediaSource mediaSourceCreateMediaSource = this.mediaSourceFactory.createMediaSource(mediaItem);
            MediaItem.AdsConfiguration adsConfiguration = mediaItem.localConfiguration.adsConfiguration;
            if (adsConfiguration == null) {
                return mediaSourceCreateMediaSource;
            }
            if (adsConfiguration.adsId instanceof String) {
                return new AdsMediaSource(mediaSourceCreateMediaSource, new DataSpec(mediaItem.localConfiguration.adsConfiguration.adTagUri), Assertions.checkNotNull(mediaItem.localConfiguration.adsConfiguration.adsId), this.mediaSourceFactory, this.adsLoader, this.adViewProvider, false);
            }
            throw new IllegalArgumentException("Please use an AdsConfiguration with an adsId of type String when using HlsInterstitialsAdsLoader");
        }

        @Override // androidx.media3.exoplayer.source.MediaSource.Factory
        public int[] getSupportedTypes() {
            return new int[]{2};
        }

        public AdsMediaSourceFactory(HlsInterstitialsAdsLoader hlsInterstitialsAdsLoader, AdViewProvider adViewProvider, MediaSource.Factory factory) {
            this(hlsInterstitialsAdsLoader, null, factory, adViewProvider);
        }

        @Override // androidx.media3.exoplayer.source.MediaSource.Factory
        @CanIgnoreReturnValue
        public AdsMediaSourceFactory setDrmSessionManagerProvider(DrmSessionManagerProvider drmSessionManagerProvider) {
            this.mediaSourceFactory.setDrmSessionManagerProvider(drmSessionManagerProvider);
            return this;
        }

        @Override // androidx.media3.exoplayer.source.MediaSource.Factory
        @CanIgnoreReturnValue
        public AdsMediaSourceFactory setLoadErrorHandlingPolicy(LoadErrorHandlingPolicy loadErrorHandlingPolicy) {
            this.mediaSourceFactory.setLoadErrorHandlingPolicy(loadErrorHandlingPolicy);
            return this;
        }

        private AdsMediaSourceFactory(HlsInterstitialsAdsLoader hlsInterstitialsAdsLoader, @Nullable Context context, @Nullable MediaSource.Factory factory, AdViewProvider adViewProvider) {
            boolean z10 = false;
            Assertions.checkArgument((context == null && factory == null) ? false : true);
            this.adsLoader = hlsInterstitialsAdsLoader;
            factory = factory == null ? new HlsMediaSource.Factory(new DefaultDataSource.Factory((Context) Assertions.checkNotNull(context))) : factory;
            this.mediaSourceFactory = factory;
            this.adViewProvider = adViewProvider;
            int[] supportedTypes = factory.getSupportedTypes();
            int length = supportedTypes.length;
            int i10 = 0;
            while (true) {
                if (i10 >= length) {
                    break;
                }
                if (supportedTypes[i10] == 2) {
                    z10 = true;
                    break;
                }
                i10++;
            }
            Assertions.checkState(z10);
        }
    }

    public static class AdsResumptionState {
        private static final String FIELD_ADS_ID = Util.intToStringMaxRadix(0);
        private static final String FIELD_AD_PLAYBACK_STATE = Util.intToStringMaxRadix(1);
        private final AdPlaybackState adPlaybackState;
        public final String adsId;

        public AdsResumptionState(String str, AdPlaybackState adPlaybackState) {
            Assertions.checkArgument(str.equals(adPlaybackState.adsId));
            this.adsId = str;
            this.adPlaybackState = adPlaybackState;
        }

        public static AdsResumptionState fromBundle(Bundle bundle) {
            String str = (String) Assertions.checkNotNull(bundle.getString(FIELD_ADS_ID));
            return new AdsResumptionState(str, AdPlaybackState.fromBundle((Bundle) Assertions.checkNotNull(bundle.getBundle(FIELD_AD_PLAYBACK_STATE))).withAdsId(str));
        }

        public boolean equals(@Nullable Object obj) {
            if (!(obj instanceof AdsResumptionState)) {
                return false;
            }
            AdsResumptionState adsResumptionState = (AdsResumptionState) obj;
            return Objects.equals(this.adsId, adsResumptionState.adsId) && Objects.equals(this.adPlaybackState, adsResumptionState.adPlaybackState);
        }

        public int hashCode() {
            return Objects.hash(this.adsId, this.adPlaybackState);
        }

        public Bundle toBundle() {
            Bundle bundle = new Bundle();
            bundle.putString(FIELD_ADS_ID, this.adsId);
            bundle.putBundle(FIELD_AD_PLAYBACK_STATE, this.adPlaybackState.toBundle());
            return bundle;
        }
    }

    public static final class Asset {
        public final long durationUs;
        public final Uri uri;

        public Asset(Uri uri, long j10) {
            this.uri = uri;
            this.durationUs = j10;
        }

        public boolean equals(@Nullable Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof Asset)) {
                return false;
            }
            Asset asset = (Asset) obj;
            return this.durationUs == asset.durationUs && Objects.equals(this.uri, asset.uri);
        }

        public int hashCode() {
            return Objects.hash(this.uri, Long.valueOf(this.durationUs));
        }
    }

    public static final class AssetList {
        static final AssetList EMPTY = new AssetList(ImmutableList.t(), ImmutableList.t());
        public final ImmutableList<Asset> assets;
        public final ImmutableList<StringAttribute> stringAttributes;

        public AssetList(ImmutableList<Asset> immutableList, ImmutableList<StringAttribute> immutableList2) {
            this.assets = immutableList;
            this.stringAttributes = immutableList2;
        }

        public boolean equals(@Nullable Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof AssetList)) {
                return false;
            }
            AssetList assetList = (AssetList) obj;
            return Objects.equals(this.assets, assetList.assets) && Objects.equals(this.stringAttributes, assetList.stringAttributes);
        }

        public int hashCode() {
            return Objects.hash(this.assets, this.stringAttributes);
        }
    }

    public static class AssetListData {
        private final int adGroupIndex;
        private final int adIndexInAdGroup;
        private final Object adsId;
        private final HlsMediaPlaylist.Interstitial interstitial;
        private final MediaItem mediaItem;
        private final long targetDurationUs;

        public AssetListData(MediaItem mediaItem, Object obj, HlsMediaPlaylist.Interstitial interstitial, int i10, int i11, long j10) {
            Assertions.checkArgument(interstitial.assetListUri != null);
            this.mediaItem = mediaItem;
            this.adsId = obj;
            this.adGroupIndex = i10;
            this.adIndexInAdGroup = i11;
            this.targetDurationUs = j10;
            this.interstitial = interstitial;
        }

        public boolean equals(@Nullable Object obj) {
            if (!(obj instanceof AssetListData)) {
                return false;
            }
            AssetListData assetListData = (AssetListData) obj;
            return this.adGroupIndex == assetListData.adGroupIndex && this.adIndexInAdGroup == assetListData.adIndexInAdGroup && this.targetDurationUs == assetListData.targetDurationUs && Objects.equals(this.mediaItem, assetListData.mediaItem) && Objects.equals(this.adsId, assetListData.adsId) && Objects.equals(this.interstitial, assetListData.interstitial);
        }

        public int hashCode() {
            return (int) ((((long) (((((this.interstitial.hashCode() + ((this.adsId.hashCode() + (this.mediaItem.hashCode() * 31)) * 31)) * 31) + this.adGroupIndex) * 31) + this.adIndexInAdGroup)) * 31) + this.targetDurationUs);
        }
    }

    public interface Listener {
        default void onAdCompleted(MediaItem mediaItem, Object obj, int i10, int i11) {
        }

        default void onAssetListLoadCompleted(MediaItem mediaItem, Object obj, int i10, int i11, AssetList assetList) {
        }

        default void onAssetListLoadFailed(MediaItem mediaItem, Object obj, int i10, int i11, @Nullable IOException iOException, boolean z10) {
        }

        default void onAssetListLoadStarted(MediaItem mediaItem, Object obj, int i10, int i11) {
        }

        default void onContentTimelineChanged(MediaItem mediaItem, Object obj, Timeline timeline) {
        }

        default void onMetadata(MediaItem mediaItem, Object obj, int i10, int i11, Metadata metadata) {
        }

        default void onPrepareCompleted(MediaItem mediaItem, Object obj, int i10, int i11) {
        }

        default void onPrepareError(MediaItem mediaItem, Object obj, int i10, int i11, IOException iOException) {
        }

        default void onStart(MediaItem mediaItem, Object obj, AdViewProvider adViewProvider) {
        }

        default void onStop(MediaItem mediaItem, Object obj, AdPlaybackState adPlaybackState) {
        }
    }

    public class LoaderCallback implements Loader.Callback<ParsingLoadable<AssetList>> {
        private final AssetListData assetListData;

        public LoaderCallback(AssetListData assetListData) {
            this.assetListData = assetListData;
        }

        private void handleAssetResolutionFailed(@Nullable final IOException iOException, final boolean z10) {
            HlsInterstitialsAdsLoader.this.notifyAssetResolutionFailed(this.assetListData.adsId, this.assetListData.adGroupIndex, this.assetListData.adIndexInAdGroup);
            HlsInterstitialsAdsLoader.this.notifyListeners(new Consumer() { // from class: androidx.media3.exoplayer.hls.d
                @Override // androidx.media3.common.util.Consumer
                public final void accept(Object obj) {
                    this.f3028a.lambda$handleAssetResolutionFailed$1(iOException, z10, (HlsInterstitialsAdsLoader.Listener) obj);
                }
            });
            maybeContinueAssetResolution();
        }

        /* JADX INFO: Access modifiers changed from: private */
        public /* synthetic */ void lambda$handleAssetResolutionFailed$1(IOException iOException, boolean z10, Listener listener) {
            listener.onAssetListLoadFailed(this.assetListData.mediaItem, this.assetListData.adsId, this.assetListData.adGroupIndex, this.assetListData.adIndexInAdGroup, iOException, z10);
        }

        /* JADX INFO: Access modifiers changed from: private */
        public /* synthetic */ void lambda$onLoadCompleted$0(AssetList assetList, Listener listener) {
            listener.onAssetListLoadCompleted(this.assetListData.mediaItem, this.assetListData.adsId, this.assetListData.adGroupIndex, this.assetListData.adIndexInAdGroup, assetList);
        }

        private void maybeContinueAssetResolution() {
            ExoPlayer exoPlayer = HlsInterstitialsAdsLoader.this.player;
            if (exoPlayer == null || exoPlayer.getPlaybackState() == 1 || !this.assetListData.mediaItem.equals(exoPlayer.getCurrentMediaItem())) {
                return;
            }
            long jMsToUs = Util.msToUs(exoPlayer.getContentPosition());
            Timeline currentTimeline = exoPlayer.getCurrentTimeline();
            long unresolvedAssetListWindowPositionForContentPositionUs = HlsInterstitialsAdsLoader.this.getUnresolvedAssetListWindowPositionForContentPositionUs(jMsToUs, currentTimeline, exoPlayer.getCurrentPeriodIndex());
            HlsInterstitialsAdsLoader hlsInterstitialsAdsLoader = HlsInterstitialsAdsLoader.this;
            Object obj = this.assetListData.adsId;
            int currentMediaItemIndex = exoPlayer.getCurrentMediaItemIndex();
            if (unresolvedAssetListWindowPositionForContentPositionUs != -9223372036854775807L) {
                jMsToUs = unresolvedAssetListWindowPositionForContentPositionUs;
            }
            hlsInterstitialsAdsLoader.maybeExecuteOrSetNextAssetListResolutionMessage(obj, currentTimeline, currentMediaItemIndex, jMsToUs);
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Callback
        public void onLoadCanceled(ParsingLoadable<AssetList> parsingLoadable, long j10, long j11, boolean z10) {
            handleAssetResolutionFailed(null, true);
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Callback
        public void onLoadCompleted(ParsingLoadable<AssetList> parsingLoadable, long j10, long j11) {
            AssetList result = parsingLoadable.getResult();
            AdPlaybackState adPlaybackStateWithAvailableAdMediaItem = (AdPlaybackState) HlsInterstitialsAdsLoader.this.activeAdPlaybackStates.get(this.assetListData.adsId);
            int i10 = 0;
            if (adPlaybackStateWithAvailableAdMediaItem == null || result == null || result.assets.isEmpty()) {
                if (adPlaybackStateWithAvailableAdMediaItem != null) {
                    handleAssetResolutionFailed(new IOException("empty asset list"), false);
                    return;
                }
                return;
            }
            AdPlaybackState.AdGroup adGroup = adPlaybackStateWithAvailableAdMediaItem.getAdGroup(this.assetListData.adGroupIndex);
            long j12 = 0;
            long j13 = adGroup.durationsUs[this.assetListData.adIndexInAdGroup] != -9223372036854775807L ? adGroup.durationsUs[this.assetListData.adIndexInAdGroup] : 0L;
            int i11 = adGroup.count;
            if (result.assets.size() > 1) {
                adPlaybackStateWithAvailableAdMediaItem = adPlaybackStateWithAvailableAdMediaItem.withAdCount(this.assetListData.adGroupIndex, (result.assets.size() + i11) - 1);
                adGroup = adPlaybackStateWithAvailableAdMediaItem.getAdGroup(this.assetListData.adGroupIndex);
            }
            int i12 = this.assetListData.adIndexInAdGroup;
            long[] jArr = (long[]) adGroup.durationsUs.clone();
            for (int i13 = 0; i13 < result.assets.size(); i13++) {
                Asset asset = result.assets.get(i13);
                if (i13 > 0) {
                    i12 = (i11 + i13) - 1;
                }
                long j14 = asset.durationUs;
                jArr[i12] = j14;
                j12 += j14;
                adPlaybackStateWithAvailableAdMediaItem = adPlaybackStateWithAvailableAdMediaItem.withAvailableAdMediaItem(this.assetListData.adGroupIndex, i12, new MediaItem.Builder().setUri(asset.uri).setMimeType(MimeTypes.APPLICATION_M3U8).build());
            }
            AdPlaybackState adPlaybackStateWithAdDurationsUs = adPlaybackStateWithAvailableAdMediaItem.withAdDurationsUs(this.assetListData.adGroupIndex, jArr);
            if (this.assetListData.interstitial.resumeOffsetUs == -9223372036854775807L) {
                adPlaybackStateWithAdDurationsUs = adPlaybackStateWithAdDurationsUs.withContentResumeOffsetUs(this.assetListData.adGroupIndex, (adPlaybackStateWithAdDurationsUs.getAdGroup(this.assetListData.adGroupIndex).contentResumeOffsetUs - j13) + j12);
            }
            HlsInterstitialsAdsLoader.this.putAndNotifyAdPlaybackStateUpdate(this.assetListData.adsId, adPlaybackStateWithAdDurationsUs);
            HlsInterstitialsAdsLoader.this.notifyListeners(new e(this, result, i10));
            maybeContinueAssetResolution();
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Callback
        public Loader.LoadErrorAction onLoadError(ParsingLoadable<AssetList> parsingLoadable, long j10, long j11, IOException iOException, int i10) {
            handleAssetResolutionFailed(iOException, false);
            return Loader.DONT_RETRY;
        }
    }

    public class PlayerListener implements Player.Listener {
        private final Timeline.Period period;

        private PlayerListener() {
            this.period = new Timeline.Period();
        }

        private void markAdAsPlayedAndNotifyListeners(MediaItem mediaItem, Object obj, int i10, int i11) {
            AdPlaybackState adPlaybackState = (AdPlaybackState) HlsInterstitialsAdsLoader.this.activeAdPlaybackStates.get(obj);
            if (adPlaybackState == null || adPlaybackState.getAdGroup(i10).states[i11] != 1) {
                return;
            }
            HlsInterstitialsAdsLoader.this.putAndNotifyAdPlaybackStateUpdate(obj, adPlaybackState.withPlayedAd(i10, i11));
            HlsInterstitialsAdsLoader.this.notifyListeners(new g(mediaItem, obj, i10, i11, 0));
        }

        @Override // androidx.media3.common.Player.Listener
        public void onMetadata(Metadata metadata) {
            ExoPlayer exoPlayer = HlsInterstitialsAdsLoader.this.player;
            if (exoPlayer == null || !exoPlayer.isPlayingAd()) {
                return;
            }
            exoPlayer.getCurrentTimeline().getPeriod(exoPlayer.getCurrentPeriodIndex(), this.period);
            Object obj = this.period.adPlaybackState.adsId;
            if (obj == null || !HlsInterstitialsAdsLoader.this.activeAdPlaybackStates.containsKey(obj)) {
                return;
            }
            HlsInterstitialsAdsLoader.this.notifyListeners(new f((MediaItem) Assertions.checkNotNull(exoPlayer.getCurrentMediaItem()), obj, exoPlayer.getCurrentAdGroupIndex(), exoPlayer.getCurrentAdIndexInAdGroup(), metadata, 0));
        }

        @Override // androidx.media3.common.Player.Listener
        public void onPlaybackStateChanged(int i10) {
            ExoPlayer exoPlayer = HlsInterstitialsAdsLoader.this.player;
            if (i10 == 4 && exoPlayer != null && exoPlayer.isPlayingAd()) {
                exoPlayer.getCurrentTimeline().getPeriod(exoPlayer.getCurrentPeriodIndex(), this.period);
                Object obj = this.period.adPlaybackState.adsId;
                if (obj == null || !HlsInterstitialsAdsLoader.this.activeAdPlaybackStates.containsKey(obj)) {
                    return;
                }
                markAdAsPlayedAndNotifyListeners((MediaItem) Assertions.checkNotNull(exoPlayer.getCurrentMediaItem()), obj, exoPlayer.getCurrentAdGroupIndex(), exoPlayer.getCurrentAdIndexInAdGroup());
            }
        }

        @Override // androidx.media3.common.Player.Listener
        public void onPositionDiscontinuity(Player.PositionInfo positionInfo, Player.PositionInfo positionInfo2, int i10) {
            if (HlsInterstitialsAdsLoader.this.player == null || positionInfo.mediaItem == null || positionInfo2.mediaItem == null || i10 == 4) {
                HlsInterstitialsAdsLoader.this.cancelPendingAssetListResolutionMessage();
                return;
            }
            Timeline currentTimeline = HlsInterstitialsAdsLoader.this.player.getCurrentTimeline();
            Object obj = currentTimeline.getPeriod(positionInfo2.periodIndex, this.period).adPlaybackState.adsId;
            if (obj == null || !HlsInterstitialsAdsLoader.this.activeAdPlaybackStates.containsKey(obj)) {
                HlsInterstitialsAdsLoader.this.cancelPendingAssetListResolutionMessage();
                return;
            }
            if ((i10 == 0 || i10 == 3) && positionInfo.adGroupIndex != -1) {
                currentTimeline.getPeriod(positionInfo.periodIndex, this.period);
                markAdAsPlayedAndNotifyListeners(positionInfo.mediaItem, obj, positionInfo.adGroupIndex, positionInfo.adIndexInAdGroup);
            } else if (i10 == 1 || i10 == 2) {
                long jMsToUs = Util.msToUs(positionInfo2.contentPositionMs);
                long unresolvedAssetListWindowPositionForContentPositionUs = HlsInterstitialsAdsLoader.this.getUnresolvedAssetListWindowPositionForContentPositionUs(jMsToUs, currentTimeline, positionInfo2.periodIndex);
                HlsInterstitialsAdsLoader.this.maybeExecuteOrSetNextAssetListResolutionMessage(obj, currentTimeline, positionInfo2.mediaItemIndex, unresolvedAssetListWindowPositionForContentPositionUs != -9223372036854775807L ? unresolvedAssetListWindowPositionForContentPositionUs : jMsToUs);
            }
        }

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

    public static class RunnableAtPosition implements Runnable {
        public final long adStartTimeUs;
        private final Runnable runnable;
        private final long targetDurationUs;

        public RunnableAtPosition(long j10, long j11, Runnable runnable) {
            this.adStartTimeUs = j10;
            this.targetDurationUs = j11;
            this.runnable = runnable;
        }

        @Override // java.lang.Runnable
        public void run() {
            this.runnable.run();
        }
    }

    public static final class StringAttribute {
        public final String name;
        public final String value;

        public StringAttribute(String str, String str2) {
            this.name = str;
            this.value = str2;
        }

        public boolean equals(@Nullable Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof StringAttribute)) {
                return false;
            }
            StringAttribute stringAttribute = (StringAttribute) obj;
            return Objects.equals(this.name, stringAttribute.name) && Objects.equals(this.value, stringAttribute.value);
        }

        public int hashCode() {
            return Objects.hash(this.name, this.value);
        }
    }

    public HlsInterstitialsAdsLoader(Context context) {
        this(new DefaultDataSource.Factory(context));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void cancelPendingAssetListResolutionMessage() {
        PlayerMessage playerMessage = this.pendingAssetListResolutionMessage;
        if (playerMessage != null) {
            playerMessage.cancel();
            this.pendingAssetListResolutionMessage = null;
        }
    }

    private static long getClosestSegmentBoundaryUs(long j10, HlsMediaPlaylist hlsMediaPlaylist) {
        long j11;
        long j12;
        long j13 = j10 - hlsMediaPlaylist.startTimeUs;
        if (j13 <= 0 || hlsMediaPlaylist.segments.isEmpty()) {
            return hlsMediaPlaylist.startTimeUs;
        }
        long j14 = hlsMediaPlaylist.durationUs;
        if (j13 >= j14) {
            return hlsMediaPlaylist.startTimeUs + j14;
        }
        HlsMediaPlaylist.Segment segment = hlsMediaPlaylist.segments.get((int) Math.min(j13 / hlsMediaPlaylist.targetDurationUs, hlsMediaPlaylist.segments.size() - 1));
        long j15 = segment.relativeStartTimeUs;
        if (j13 - j15 < Math.abs(j13 - (j15 + segment.durationUs))) {
            j11 = hlsMediaPlaylist.startTimeUs;
            j12 = segment.relativeStartTimeUs;
        } else {
            j11 = hlsMediaPlaylist.startTimeUs + segment.relativeStartTimeUs;
            j12 = segment.durationUs;
        }
        return j11 + j12;
    }

    private Loader getLoader() {
        if (this.loader == null) {
            this.loader = new Loader("HLS-interstitials");
        }
        return this.loader;
    }

    private static int getLowestValidAdGroupInsertionIndex(AdPlaybackState adPlaybackState) {
        int i10 = adPlaybackState.adGroupCount;
        while (true) {
            i10--;
            int i11 = adPlaybackState.removedAdGroupCount;
            if (i10 < i11) {
                return i11;
            }
            for (int i12 : adPlaybackState.getAdGroup(i10).states) {
                if (i12 != 0) {
                    return i10 + 1;
                }
            }
        }
    }

    @Nullable
    private RunnableAtPosition getNextAssetResolution(Object obj, long j10) {
        final TreeMap treeMap = (TreeMap) Assertions.checkNotNull(this.unresolvedAssetLists.get(obj));
        for (final Long l10 : treeMap.keySet()) {
            if (treeMap.size() == 1 || j10 <= l10.longValue()) {
                final AssetListData assetListData = (AssetListData) Assertions.checkNotNull((AssetListData) treeMap.get(l10));
                return new RunnableAtPosition(l10.longValue(), assetListData.targetDurationUs, new Runnable() { // from class: androidx.media3.exoplayer.hls.c
                    @Override // java.lang.Runnable
                    public final void run() {
                        this.f3024a.lambda$getNextAssetResolution$7(treeMap, l10, assetListData);
                    }
                });
            }
        }
        return null;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public long getUnresolvedAssetListWindowPositionForContentPositionUs(long j10, Timeline timeline, int i10) {
        Timeline.Period period = timeline.getPeriod(i10, new Timeline.Period());
        long j11 = j10 - period.positionInWindowUs;
        AdPlaybackState adPlaybackState = period.adPlaybackState;
        int adGroupIndexForPositionUs = adPlaybackState.getAdGroupIndexForPositionUs(j11, -9223372036854775807L);
        if (adGroupIndexForPositionUs != -1) {
            AdPlaybackState.AdGroup adGroup = adPlaybackState.getAdGroup(adGroupIndexForPositionUs);
            TreeMap<Long, AssetListData> treeMap = this.unresolvedAssetLists.get(adPlaybackState.adsId);
            if (treeMap != null && treeMap.containsKey(Long.valueOf(adGroup.timeUs))) {
                return adGroup.timeUs - timeline.getWindow(period.windowIndex, new Timeline.Window()).positionInFirstPeriodUs;
            }
        }
        return -9223372036854775807L;
    }

    private AdPlaybackState insertOrUpdateInterstitialInAdGroup(MediaItem mediaItem, HlsMediaPlaylist.Interstitial interstitial, AdPlaybackState adPlaybackState, int i10, long j10) {
        long[] jArr;
        AdPlaybackState.AdGroup adGroup = adPlaybackState.getAdGroup(i10);
        if (adGroup.getIndexOfAdId(interstitial.f3049id) != -1) {
            return adPlaybackState;
        }
        int iMax = Math.max(adGroup.count, 0);
        long jResolveInterstitialDurationUs = resolveInterstitialDurationUs(interstitial, -9223372036854775807L);
        if (iMax == 0) {
            jArr = new long[1];
        } else {
            long[] jArr2 = adGroup.durationsUs;
            long[] jArr3 = new long[jArr2.length + 1];
            System.arraycopy(jArr2, 0, jArr3, 0, jArr2.length);
            jArr = jArr3;
        }
        jArr[jArr.length - 1] = jResolveInterstitialDurationUs;
        long j11 = interstitial.resumeOffsetUs;
        if (j11 != -9223372036854775807L) {
            jResolveInterstitialDurationUs = j11;
        } else if (jResolveInterstitialDurationUs == -9223372036854775807L) {
            jResolveInterstitialDurationUs = 0;
        }
        AdPlaybackState adPlaybackStateWithContentResumeOffsetUs = adPlaybackState.withAdCount(i10, iMax + 1).withAdId(i10, iMax, interstitial.f3049id).withAdDurationsUs(i10, jArr).withContentResumeOffsetUs(i10, adGroup.contentResumeOffsetUs + jResolveInterstitialDurationUs);
        if (interstitial.assetUri != null) {
            return adPlaybackStateWithContentResumeOffsetUs.withAvailableAdMediaItem(i10, iMax, new MediaItem.Builder().setUri(interstitial.assetUri).setMimeType(MimeTypes.APPLICATION_M3U8).build());
        }
        Object objCheckNotNull = Assertions.checkNotNull(adPlaybackStateWithContentResumeOffsetUs.adsId);
        TreeMap treeMap = (TreeMap) Assertions.checkNotNull(this.unresolvedAssetLists.get(objCheckNotNull));
        long j12 = adGroup.timeUs;
        if (j12 == Long.MIN_VALUE) {
            j12 = Long.MAX_VALUE;
        }
        treeMap.put(Long.valueOf(j12), new AssetListData(mediaItem, objCheckNotNull, interstitial, i10, iMax, j10));
        return adPlaybackStateWithContentResumeOffsetUs;
    }

    private static boolean isHlsMediaItem(MediaItem mediaItem) {
        MediaItem.LocalConfiguration localConfiguration = (MediaItem.LocalConfiguration) Assertions.checkNotNull(mediaItem.localConfiguration);
        return Objects.equals(localConfiguration.mimeType, MimeTypes.APPLICATION_M3U8) || Util.inferContentType(localConfiguration.uri) == 2;
    }

    private static boolean isLiveMediaItem(MediaItem mediaItem, Timeline timeline) {
        int firstWindowIndex = timeline.getFirstWindowIndex(false);
        Timeline.Window window = new Timeline.Window();
        while (firstWindowIndex != -1) {
            timeline.getWindow(firstWindowIndex, window);
            if (window.mediaItem.equals(mediaItem)) {
                return window.isLive();
            }
            firstWindowIndex = timeline.getNextWindowIndex(firstWindowIndex, 0, false);
        }
        return false;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$getNextAssetResolution$7(TreeMap treeMap, Long l10, AssetListData assetListData) {
        if (treeMap.remove(l10) != null) {
            startLoadingAssetList(assetListData);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static /* synthetic */ void lambda$handleContentTimelineChanged$1(AdsMediaSource adsMediaSource, Object obj, Timeline timeline, Listener listener) {
        listener.onContentTimelineChanged(adsMediaSource.getMediaItem(), obj, timeline);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static /* synthetic */ void lambda$handlePrepareComplete$2(AdsMediaSource adsMediaSource, Object obj, int i10, int i11, Listener listener) {
        listener.onPrepareCompleted(adsMediaSource.getMediaItem(), obj, i10, i11);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static /* synthetic */ void lambda$handlePrepareError$3(AdsMediaSource adsMediaSource, Object obj, int i10, int i11, IOException iOException, Listener listener) {
        listener.onPrepareError(adsMediaSource.getMediaItem(), obj, i10, i11, iOException);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static /* synthetic */ void lambda$startLoadingAssetList$5(AssetListData assetListData, Listener listener) {
        listener.onAssetListLoadStarted(assetListData.mediaItem, assetListData.adsId, assetListData.adGroupIndex, assetListData.adIndexInAdGroup);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static /* synthetic */ void lambda$stop$4(AdsMediaSource adsMediaSource, AdPlaybackState adPlaybackState, Listener listener) {
        listener.onStop(adsMediaSource.getMediaItem(), adsMediaSource.getAdsId(), (AdPlaybackState) Assertions.checkNotNull(adPlaybackState));
    }

    private AdPlaybackState mapInterstitialsForLive(MediaItem mediaItem, HlsMediaPlaylist hlsMediaPlaylist, AdPlaybackState adPlaybackState, long j10, Set<String> set) {
        boolean z10;
        int i10;
        ArrayList arrayList = new ArrayList(hlsMediaPlaylist.interstitials);
        AdPlaybackState adPlaybackStateInsertOrUpdateInterstitialInAdGroup = adPlaybackState;
        for (int i11 = 0; i11 < arrayList.size(); i11++) {
            HlsMediaPlaylist.Interstitial interstitial = (HlsMediaPlaylist.Interstitial) arrayList.get(i11);
            if (!set.contains(interstitial.f3049id) && !interstitial.cue.contains(HlsMediaPlaylist.Interstitial.CUE_TRIGGER_POST)) {
                long jResolveInterstitialStartTimeUs = resolveInterstitialStartTimeUs(interstitial, hlsMediaPlaylist) - hlsMediaPlaylist.startTimeUs;
                if (jResolveInterstitialStartTimeUs >= 0) {
                    if ((hlsMediaPlaylist.targetDurationUs * 3) + hlsMediaPlaylist.durationUs >= jResolveInterstitialStartTimeUs) {
                        long j11 = j10 + jResolveInterstitialStartTimeUs;
                        int i12 = adPlaybackStateInsertOrUpdateInterstitialInAdGroup.adGroupCount;
                        int i13 = i12 - 1;
                        int i14 = i12 - 2;
                        while (true) {
                            int i15 = i13;
                            i13 = i14;
                            z10 = true;
                            if (i13 < adPlaybackStateInsertOrUpdateInterstitialInAdGroup.removedAdGroupCount) {
                                i10 = i15;
                                break;
                            }
                            long j12 = adPlaybackStateInsertOrUpdateInterstitialInAdGroup.getAdGroup(i13).timeUs;
                            if (j12 == j11) {
                                z10 = false;
                                break;
                            }
                            if (j12 < j11) {
                                i13++;
                                break;
                            }
                            i14 = i13 - 1;
                        }
                        i10 = i13;
                        if (!z10) {
                            adPlaybackStateInsertOrUpdateInterstitialInAdGroup = insertOrUpdateInterstitialInAdGroup(mediaItem, interstitial, adPlaybackStateInsertOrUpdateInterstitialInAdGroup, i10, hlsMediaPlaylist.targetDurationUs);
                            set.add(interstitial.f3049id);
                        } else if (i10 < getLowestValidAdGroupInsertionIndex(adPlaybackStateInsertOrUpdateInterstitialInAdGroup)) {
                            Log.w(TAG, "Skipping insertion of interstitial attempted to be inserted behind an already initialized ad group.");
                        } else {
                            adPlaybackStateInsertOrUpdateInterstitialInAdGroup = adPlaybackStateInsertOrUpdateInterstitialInAdGroup.withNewAdGroup(i10, j11);
                            adPlaybackStateInsertOrUpdateInterstitialInAdGroup = insertOrUpdateInterstitialInAdGroup(mediaItem, interstitial, adPlaybackStateInsertOrUpdateInterstitialInAdGroup, i10, hlsMediaPlaylist.targetDurationUs);
                            set.add(interstitial.f3049id);
                        }
                    }
                }
            }
        }
        return adPlaybackStateInsertOrUpdateInterstitialInAdGroup;
    }

    private AdPlaybackState mapInterstitialsForVod(Timeline.Window window, HlsMediaPlaylist hlsMediaPlaylist, AdPlaybackState adPlaybackState, Set<String> set) {
        ImmutableList<HlsMediaPlaylist.Interstitial> immutableList;
        AdPlaybackState adPlaybackStateWithNewAdGroup = adPlaybackState;
        int i10 = 0;
        Assertions.checkArgument(adPlaybackStateWithNewAdGroup.adGroupCount == adPlaybackStateWithNewAdGroup.removedAdGroupCount);
        ImmutableList<HlsMediaPlaylist.Interstitial> immutableList2 = hlsMediaPlaylist.interstitials;
        long j10 = hlsMediaPlaylist.startTimeUs + window.positionInFirstPeriodUs;
        long j11 = window.durationUs + j10;
        while (i10 < immutableList2.size()) {
            HlsMediaPlaylist.Interstitial interstitial = immutableList2.get(i10);
            long jResolveInterstitialStartTimeUs = resolveInterstitialStartTimeUs(interstitial, hlsMediaPlaylist);
            if (jResolveInterstitialStartTimeUs < j10 && interstitial.cue.contains(HlsMediaPlaylist.Interstitial.CUE_TRIGGER_PRE)) {
                jResolveInterstitialStartTimeUs = j10;
            } else if (jResolveInterstitialStartTimeUs <= j11 || !interstitial.cue.contains(HlsMediaPlaylist.Interstitial.CUE_TRIGGER_POST)) {
                if (jResolveInterstitialStartTimeUs < j10 || j11 < jResolveInterstitialStartTimeUs) {
                    immutableList = immutableList2;
                }
                i10++;
                immutableList2 = immutableList;
            } else {
                jResolveInterstitialStartTimeUs = j11;
            }
            long j12 = j11 == jResolveInterstitialStartTimeUs ? Long.MIN_VALUE : jResolveInterstitialStartTimeUs - hlsMediaPlaylist.startTimeUs;
            int adGroupIndexForPositionUs = adPlaybackStateWithNewAdGroup.getAdGroupIndexForPositionUs(j12, hlsMediaPlaylist.durationUs);
            if (adGroupIndexForPositionUs == -1) {
                adGroupIndexForPositionUs = adPlaybackStateWithNewAdGroup.removedAdGroupCount;
                adPlaybackStateWithNewAdGroup = adPlaybackStateWithNewAdGroup.withNewAdGroup(adGroupIndexForPositionUs, j12);
            } else if (adPlaybackStateWithNewAdGroup.getAdGroup(adGroupIndexForPositionUs).timeUs != j12) {
                adGroupIndexForPositionUs++;
                adPlaybackStateWithNewAdGroup = adPlaybackStateWithNewAdGroup.withNewAdGroup(adGroupIndexForPositionUs, j12);
            }
            immutableList = immutableList2;
            adPlaybackStateWithNewAdGroup = insertOrUpdateInterstitialInAdGroup(window.mediaItem, interstitial, adPlaybackStateWithNewAdGroup, adGroupIndexForPositionUs, hlsMediaPlaylist.targetDurationUs);
            set.add(interstitial.f3049id);
            i10++;
            immutableList2 = immutableList;
        }
        return adPlaybackStateWithNewAdGroup;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void maybeExecuteOrSetNextAssetListResolutionMessage(Object obj, Timeline timeline, int i10, long j10) {
        Loader loader = this.loader;
        if (loader == null || !loader.isLoading()) {
            cancelPendingAssetListResolutionMessage();
            Timeline.Window window = timeline.getWindow(i10, new Timeline.Window());
            long j11 = window.positionInFirstPeriodUs + j10;
            RunnableAtPosition nextAssetResolution = getNextAssetResolution(obj, j11);
            if (nextAssetResolution == null) {
                return;
            }
            long j12 = nextAssetResolution.adStartTimeUs;
            if (j12 == Long.MAX_VALUE) {
                j12 = window.durationUs;
            }
            long jMax = Math.max(j11, j12 - (nextAssetResolution.targetDurationUs * 3));
            if (jMax - j11 < 200000) {
                nextAssetResolution.run();
                return;
            }
            PlayerMessage position = ((ExoPlayer) Assertions.checkNotNull(this.player)).createMessage(new a(nextAssetResolution)).setPayload(window.mediaItem).setLooper((Looper) Assertions.checkNotNull(Looper.myLooper())).setPosition(Util.usToMs(jMax - window.positionInFirstPeriodUs));
            this.pendingAssetListResolutionMessage = position;
            position.send();
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void notifyAssetResolutionFailed(Object obj, int i10, int i11) {
        AdPlaybackState adPlaybackState = this.activeAdPlaybackStates.get(obj);
        if (adPlaybackState == null) {
            return;
        }
        putAndNotifyAdPlaybackStateUpdate(obj, adPlaybackState.withAdLoadError(i10, i11));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void notifyListeners(Consumer<Listener> consumer) {
        for (int i10 = 0; i10 < this.listeners.size(); i10++) {
            consumer.accept(this.listeners.get(i10));
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public boolean putAndNotifyAdPlaybackStateUpdate(Object obj, AdPlaybackState adPlaybackState) {
        if (adPlaybackState.equals(this.activeAdPlaybackStates.put(obj, adPlaybackState))) {
            return false;
        }
        AdsLoader.EventListener eventListener = this.activeEventListeners.get(obj);
        if (eventListener != null) {
            eventListener.onAdPlaybackState(adPlaybackState);
            return true;
        }
        this.activeAdPlaybackStates.remove(obj);
        this.insertedInterstitialIds.remove(obj);
        return false;
    }

    private static long resolveInterstitialDurationUs(HlsMediaPlaylist.Interstitial interstitial, long j10) {
        long j11 = interstitial.playoutLimitUs;
        if (j11 != -9223372036854775807L) {
            return j11;
        }
        long j12 = interstitial.durationUs;
        if (j12 != -9223372036854775807L) {
            return j12;
        }
        long j13 = interstitial.endDateUnixUs;
        if (j13 != -9223372036854775807L) {
            return j13 - interstitial.startDateUnixUs;
        }
        long j14 = interstitial.plannedDurationUs;
        return j14 != -9223372036854775807L ? j14 : j10;
    }

    private static long resolveInterstitialStartTimeUs(HlsMediaPlaylist.Interstitial interstitial, HlsMediaPlaylist hlsMediaPlaylist) {
        if (interstitial.cue.contains(HlsMediaPlaylist.Interstitial.CUE_TRIGGER_PRE)) {
            return hlsMediaPlaylist.startTimeUs;
        }
        if (interstitial.cue.contains(HlsMediaPlaylist.Interstitial.CUE_TRIGGER_POST)) {
            return hlsMediaPlaylist.startTimeUs + hlsMediaPlaylist.durationUs;
        }
        if (interstitial.snapTypes.contains(HlsMediaPlaylist.Interstitial.SNAP_TYPE_OUT)) {
            return getClosestSegmentBoundaryUs(interstitial.startDateUnixUs, hlsMediaPlaylist);
        }
        if (!interstitial.snapTypes.contains(HlsMediaPlaylist.Interstitial.SNAP_TYPE_IN)) {
            return interstitial.startDateUnixUs;
        }
        long jResolveInterstitialDurationUs = interstitial.resumeOffsetUs;
        if (jResolveInterstitialDurationUs == -9223372036854775807L) {
            jResolveInterstitialDurationUs = resolveInterstitialDurationUs(interstitial, 0L);
        }
        return getClosestSegmentBoundaryUs(interstitial.startDateUnixUs + jResolveInterstitialDurationUs, hlsMediaPlaylist) - jResolveInterstitialDurationUs;
    }

    private void startLoadingAssetList(AssetListData assetListData) {
        cancelPendingAssetListResolutionMessage();
        getLoader().startLoading(new ParsingLoadable(this.dataSourceFactory.createDataSource(), (Uri) Assertions.checkNotNull(assetListData.interstitial.assetListUri), 6, new AssetListParser()), new LoaderCallback(assetListData), 1);
        notifyListeners(new a(assetListData));
    }

    public void addAdResumptionState(AdsResumptionState adsResumptionState) {
        addAdResumptionState(adsResumptionState.adsId, adsResumptionState.adPlaybackState);
    }

    public void addListener(Listener listener) {
        this.listeners.add(listener);
    }

    public void clearAllAdResumptionStates() {
        this.resumptionStates.clear();
    }

    public ImmutableList<AdsResumptionState> getAdsResumptionStates() {
        m0 m0Var = new m0(4);
        for (AdPlaybackState adPlaybackState : this.activeAdPlaybackStates.values()) {
            boolean zEndsWithLivePostrollPlaceHolder = adPlaybackState.endsWithLivePostrollPlaceHolder();
            if (zEndsWithLivePostrollPlaceHolder || !(adPlaybackState.adsId instanceof String)) {
                Log.i(TAG, zEndsWithLivePostrollPlaceHolder ? "getAdsResumptionStates(): ignoring active ad playback state of live stream. adsId=" + adPlaybackState.adsId : "getAdsResumptionStates(): ignoring active ad playback state when creating resumption states. `adsId` is not of type String: " + Util.castNonNull(adPlaybackState.adsId).getClass());
            } else {
                m0Var.c(new AdsResumptionState((String) adPlaybackState.adsId, adPlaybackState.copy()));
            }
        }
        return m0Var.i();
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public boolean handleContentTimelineChanged(AdsMediaSource adsMediaSource, Timeline timeline) {
        long jMsToUs;
        Object adsId = adsMediaSource.getAdsId();
        int i10 = 0;
        if (this.isReleased) {
            AdsLoader.EventListener eventListenerRemove = this.activeEventListeners.remove(adsId);
            if (eventListenerRemove != null) {
                this.unsupportedAdsIds.remove(adsId);
                AdPlaybackState adPlaybackState = (AdPlaybackState) Assertions.checkNotNull(this.activeAdPlaybackStates.remove(adsId));
                this.insertedInterstitialIds.remove(adsId);
                if (adPlaybackState.equals(AdPlaybackState.NONE)) {
                    eventListenerRemove.onAdPlaybackState(new AdPlaybackState(adsId, new long[0]));
                }
            }
            return false;
        }
        AdPlaybackState adPlaybackState2 = (AdPlaybackState) Assertions.checkNotNull(this.activeAdPlaybackStates.get(adsId));
        AdPlaybackState adPlaybackState3 = AdPlaybackState.NONE;
        if (!adPlaybackState2.equals(adPlaybackState3) && !adPlaybackState2.endsWithLivePostrollPlaceHolder()) {
            return false;
        }
        if (adPlaybackState2.equals(adPlaybackState3)) {
            adPlaybackState2 = new AdPlaybackState(adsId, new long[0]);
            if (isLiveMediaItem(adsMediaSource.getMediaItem(), timeline)) {
                adPlaybackState2 = adPlaybackState2.withLivePostrollPlaceholderAppended(false);
            }
        }
        AdPlaybackState adPlaybackState4 = adPlaybackState2;
        Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
        Object obj = window.manifest;
        if (obj instanceof HlsManifest) {
            HlsMediaPlaylist hlsMediaPlaylist = ((HlsManifest) obj).mediaPlaylist;
            TreeMap treeMap = (TreeMap) Assertions.checkNotNull(this.unresolvedAssetLists.get(adsId));
            int size = treeMap.size();
            AdPlaybackState adPlaybackStateMapInterstitialsForLive = window.isLive() ? mapInterstitialsForLive(window.mediaItem, hlsMediaPlaylist, adPlaybackState4, window.positionInFirstPeriodUs, (Set) Assertions.checkNotNull(this.insertedInterstitialIds.get(adsId))) : mapInterstitialsForVod(window, hlsMediaPlaylist, adPlaybackState4, (Set) Assertions.checkNotNull(this.insertedInterstitialIds.get(adsId)));
            ExoPlayer exoPlayer = this.player;
            if (size != treeMap.size() && exoPlayer != null && Objects.equals(window.mediaItem, exoPlayer.getCurrentMediaItem())) {
                if (window.isLive()) {
                    jMsToUs = exoPlayer.getCurrentTimeline().getPeriod(exoPlayer.getCurrentPeriodIndex(), new Timeline.Period()).isPlaceholder ? window.defaultPositionUs : Util.msToUs(exoPlayer.getContentPosition());
                } else {
                    jMsToUs = Util.msToUs(exoPlayer.getContentPosition());
                }
                int adGroupIndexForPositionUs = adPlaybackStateMapInterstitialsForLive.getAdGroupIndexForPositionUs(jMsToUs, window.durationUs);
                if (adGroupIndexForPositionUs != -1) {
                    jMsToUs = adPlaybackStateMapInterstitialsForLive.getAdGroup(adGroupIndexForPositionUs).timeUs;
                }
                maybeExecuteOrSetNextAssetListResolutionMessage(adsId, timeline, 0, jMsToUs);
            }
            adPlaybackState4 = adPlaybackStateMapInterstitialsForLive;
        }
        boolean zPutAndNotifyAdPlaybackStateUpdate = putAndNotifyAdPlaybackStateUpdate(adsId, adPlaybackState4);
        if (!this.unsupportedAdsIds.contains(adsId)) {
            notifyListeners(new b(adsMediaSource, adsId, timeline, i10));
        }
        return zPutAndNotifyAdPlaybackStateUpdate;
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void handlePrepareComplete(AdsMediaSource adsMediaSource, int i10, int i11) {
        Object adsId = adsMediaSource.getAdsId();
        if (this.isReleased || this.unsupportedAdsIds.contains(adsId)) {
            return;
        }
        notifyListeners(new g(adsMediaSource, adsId, i10, i11, 1));
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void handlePrepareError(AdsMediaSource adsMediaSource, int i10, int i11, IOException iOException) {
        Object adsId = adsMediaSource.getAdsId();
        putAndNotifyAdPlaybackStateUpdate(adsId, ((AdPlaybackState) Assertions.checkNotNull(this.activeAdPlaybackStates.get(adsId))).withAdLoadError(i10, i11));
        if (this.isReleased || this.unsupportedAdsIds.contains(adsId)) {
            return;
        }
        notifyListeners(new f(adsMediaSource, adsId, i10, i11, iOException, 1));
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void release() {
        if (this.activeEventListeners.isEmpty()) {
            this.player = null;
        }
        clearAllAdResumptionStates();
        cancelPendingAssetListResolutionMessage();
        Loader loader = this.loader;
        if (loader != null) {
            loader.release();
            this.loader = null;
        }
        this.isReleased = true;
    }

    public boolean removeAdResumptionState(Object obj) {
        return this.resumptionStates.remove(obj) != null;
    }

    public void removeListener(Listener listener) {
        this.listeners.remove(listener);
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void setPlayer(@Nullable Player player) {
        boolean z10 = true;
        Assertions.checkState(!this.isReleased);
        Assertions.checkArgument(player == null || (player instanceof ExoPlayer));
        if (Objects.equals(this.player, player)) {
            return;
        }
        if (this.player != null && !this.activeEventListeners.isEmpty()) {
            this.player.removeListener(this.playerListener);
        }
        if (player != null && !this.activeEventListeners.isEmpty()) {
            z10 = false;
        }
        Assertions.checkState(z10);
        this.player = (ExoPlayer) player;
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void setSupportedContentTypes(int... iArr) {
        for (int i10 : iArr) {
            if (i10 == 2) {
                return;
            }
        }
        throw new IllegalArgumentException();
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void start(AdsMediaSource adsMediaSource, DataSpec dataSpec, Object obj, AdViewProvider adViewProvider, AdsLoader.EventListener eventListener) {
        if (this.isReleased) {
            eventListener.onAdPlaybackState(new AdPlaybackState(obj, new long[0]));
            return;
        }
        if (this.activeAdPlaybackStates.containsKey(obj) || this.unsupportedAdsIds.contains(obj)) {
            throw new IllegalStateException("media item with adsId='" + obj + "' already started. Make sure adsIds are unique within the same playlist.");
        }
        if (this.activeEventListeners.isEmpty()) {
            ((ExoPlayer) Assertions.checkStateNotNull(this.player, "setPlayer(Player) needs to be called")).addListener(this.playerListener);
        }
        this.activeEventListeners.put(obj, eventListener);
        MediaItem mediaItem = adsMediaSource.getMediaItem();
        if (!isHlsMediaItem(mediaItem)) {
            Log.w(TAG, "Unsupported media item. Playing without ads for adsId=" + obj);
            putAndNotifyAdPlaybackStateUpdate(obj, new AdPlaybackState(obj, new long[0]));
            this.unsupportedAdsIds.add(obj);
            return;
        }
        this.insertedInterstitialIds.put(obj, new HashSet());
        this.unresolvedAssetLists.put(obj, new TreeMap<>());
        if ((obj instanceof String) && this.resumptionStates.containsKey(obj)) {
            putAndNotifyAdPlaybackStateUpdate(obj, (AdPlaybackState) Assertions.checkNotNull(this.resumptionStates.remove(obj)));
        } else {
            this.activeAdPlaybackStates.put(obj, AdPlaybackState.NONE);
        }
        notifyListeners(new b(mediaItem, obj, adViewProvider, 1));
    }

    @Override // androidx.media3.exoplayer.source.ads.AdsLoader
    public void stop(AdsMediaSource adsMediaSource, AdsLoader.EventListener eventListener) {
        Object adsId = adsMediaSource.getAdsId();
        this.activeEventListeners.remove(adsId);
        AdPlaybackState adPlaybackStateRemove = this.activeAdPlaybackStates.remove(adsId);
        if (this.player != null && this.activeEventListeners.isEmpty()) {
            this.player.removeListener(this.playerListener);
            if (this.isReleased) {
                this.player = null;
            }
        }
        if (!this.isReleased && !this.unsupportedAdsIds.contains(adsId)) {
            if (adPlaybackStateRemove != null && (adsId instanceof String) && this.resumptionStates.containsKey(adsId)) {
                this.resumptionStates.put(adsId, adPlaybackStateRemove);
            }
            notifyListeners(new e(adsMediaSource, adPlaybackStateRemove, 1));
        }
        this.insertedInterstitialIds.remove(adsId);
        this.unsupportedAdsIds.remove(adsId);
        this.unresolvedAssetLists.remove(adsId);
        cancelPendingAssetListResolutionMessage();
        if (this.pendingAssetListResolutionMessage == null || !adsMediaSource.getMediaItem().equals(((PlayerMessage) Util.castNonNull(this.pendingAssetListResolutionMessage)).getPayload())) {
            return;
        }
        cancelPendingAssetListResolutionMessage();
    }

    public HlsInterstitialsAdsLoader(DataSource.Factory factory) {
        this.dataSourceFactory = factory;
        this.playerListener = new PlayerListener();
        this.activeEventListeners = new HashMap();
        this.activeAdPlaybackStates = new HashMap();
        this.insertedInterstitialIds = new HashMap();
        this.unresolvedAssetLists = new HashMap();
        this.resumptionStates = new HashMap();
        this.listeners = new ArrayList();
        this.unsupportedAdsIds = new HashSet();
    }

    public void addAdResumptionState(Object obj, AdPlaybackState adPlaybackState) {
        Assertions.checkArgument(!adPlaybackState.endsWithLivePostrollPlaceHolder());
        if (!this.activeAdPlaybackStates.containsKey(obj)) {
            this.resumptionStates.put(obj, adPlaybackState.copy().withAdsId(obj));
            return;
        }
        Log.w(TAG, "Attempting to add an ad resumption state for an adsId that is currently active. adsId=" + obj);
    }
}
