package androidx.media3.exoplayer.ima;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.GuardedBy;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.core.view.n;
import androidx.media3.common.AdOverlayInfo;
import androidx.media3.common.AdPlaybackState;
import androidx.media3.common.AdViewProvider;
import androidx.media3.common.C;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Metadata;
import androidx.media3.common.Player;
import androidx.media3.common.Timeline;
import androidx.media3.common.util.Assertions;
import androidx.media3.common.util.ConditionVariable;
import androidx.media3.common.util.Log;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import androidx.media3.datasource.TransferListener;
import androidx.media3.exoplayer.drm.DrmSessionManagerProvider;
import androidx.media3.exoplayer.ima.ImaUtil;
import androidx.media3.exoplayer.source.CompositeMediaSource;
import androidx.media3.exoplayer.source.ForwardingTimeline;
import androidx.media3.exoplayer.source.MediaPeriod;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.ads.ServerSideAdInsertionMediaSource;
import androidx.media3.exoplayer.source.ads.ServerSideAdInsertionUtil;
import androidx.media3.exoplayer.upstream.Allocator;
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy;
import androidx.media3.exoplayer.upstream.Loader;
import com.google.ads.interactivemedia.v3.api.Ad;
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.AdsManagerLoadedEvent;
import com.google.ads.interactivemedia.v3.api.AdsRenderingSettings;
import com.google.ads.interactivemedia.v3.api.CompanionAdSlot;
import com.google.ads.interactivemedia.v3.api.CuePoint;
import com.google.ads.interactivemedia.v3.api.FriendlyObstructionPurpose;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;
import com.google.ads.interactivemedia.v3.api.StreamDisplayContainer;
import com.google.ads.interactivemedia.v3.api.StreamManager;
import com.google.ads.interactivemedia.v3.api.StreamRequest;
import com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate;
import com.google.ads.interactivemedia.v3.api.player.VideoStreamPlayer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.q0;
import com.google.common.collect.v1;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import f2.o;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/* JADX INFO: loaded from: classes.dex */
public final class ImaServerSideAdInsertionMediaSource extends CompositeMediaSource<Void> {
    private static final String TAG = "ImaSSAIMediaSource";
    private AdPlaybackState adPlaybackState;
    private final String adsId;
    private final AdsLoader adsLoader;

    @Nullable
    private final AdErrorEvent.AdErrorListener applicationAdErrorListener;

    @Nullable
    private final AdEvent.AdEventListener applicationAdEventListener;
    private final ComponentListener componentListener;
    private final MediaSource.Factory contentMediaSourceFactory;

    @Nullable
    private Timeline contentTimeline;
    private final boolean isLiveStream;

    @Nullable
    private IOException loadError;
    private final int loadVideoTimeoutMs;

    @Nullable
    private Loader loader;
    private final Handler mainHandler;

    @GuardedBy("this")
    private MediaItem mediaItem;
    private final Player player;
    private final com.google.ads.interactivemedia.v3.api.AdsLoader sdkAdsLoader;

    @Nullable
    private ServerSideAdInsertionMediaSource serverSideAdInsertionMediaSource;
    private final StreamEventListener streamEventListener;

    @Nullable
    private String streamId;

    @Nullable
    private StreamManager streamManager;
    private final StreamPlayer streamPlayer;
    private final StreamRequest streamRequest;

    /* JADX INFO: renamed from: androidx.media3.exoplayer.ima.ImaServerSideAdInsertionMediaSource$2, reason: invalid class name */
    public static /* synthetic */ class AnonymousClass2 {
        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.CUEPOINTS_CHANGED.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.LOADED.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[AdEvent.AdEventType.SKIPPED.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
        }
    }

    public static final class AdsLoader {
        private final Map<String, AdPlaybackState> adPlaybackStateMap;
        private final ImaUtil.ServerSideAdInsertionConfiguration configuration;
        private final Context context;
        private final Map<String, MediaSourceResourceHolder> mediaSourceResources;

        @Nullable
        private Player player;

        public static final class Builder {

            @Nullable
            private AdErrorEvent.AdErrorListener adErrorListener;

            @Nullable
            private AdEvent.AdEventListener adEventListener;
            private final AdViewProvider adViewProvider;
            private final Context context;

            @Nullable
            private ImaSdkSettings imaSdkSettings;
            private ImmutableList<CompanionAdSlot> companionAdSlots = ImmutableList.t();
            private State state = new State(ImmutableMap.g());
            private boolean focusSkipButtonWhenAvailable = true;
            private StreamEventListener streamEventListener = new n(14);

            public Builder(Context context, AdViewProvider adViewProvider) {
                this.context = context;
                this.adViewProvider = adViewProvider;
            }

            /* JADX INFO: Access modifiers changed from: private */
            public static /* synthetic */ void lambda$new$0(MediaItem mediaItem, String str) {
            }

            public AdsLoader build() {
                ImaSdkSettings imaSdkSettingsCreateImaSdkSettings = this.imaSdkSettings;
                if (imaSdkSettingsCreateImaSdkSettings == null) {
                    imaSdkSettingsCreateImaSdkSettings = ImaSdkFactory.getInstance().createImaSdkSettings();
                    imaSdkSettingsCreateImaSdkSettings.setLanguage(Util.getSystemLanguageCodes()[0]);
                }
                ImaSdkSettings imaSdkSettings = imaSdkSettingsCreateImaSdkSettings;
                return new AdsLoader(this.context, new ImaUtil.ServerSideAdInsertionConfiguration(this.adViewProvider, imaSdkSettings, this.streamEventListener, this.adEventListener, this.adErrorListener, this.companionAdSlots, this.focusSkipButtonWhenAvailable, imaSdkSettings.isDebugMode()), this.state);
            }

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

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

            @CanIgnoreReturnValue
            public Builder setAdsLoaderState(State state) {
                this.state = state;
                return this;
            }

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

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

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

            @CanIgnoreReturnValue
            @UnstableApi
            public Builder setStreamEventListener(StreamEventListener streamEventListener) {
                this.streamEventListener = streamEventListener;
                return this;
            }
        }

        public static final class MediaSourceResourceHolder {
            public final com.google.ads.interactivemedia.v3.api.AdsLoader adsLoader;
            public final ImaServerSideAdInsertionMediaSource imaServerSideAdInsertionMediaSource;
            public final StreamPlayer streamPlayer;

            private MediaSourceResourceHolder(ImaServerSideAdInsertionMediaSource imaServerSideAdInsertionMediaSource, StreamPlayer streamPlayer, com.google.ads.interactivemedia.v3.api.AdsLoader adsLoader) {
                this.imaServerSideAdInsertionMediaSource = imaServerSideAdInsertionMediaSource;
                this.streamPlayer = streamPlayer;
                this.adsLoader = adsLoader;
            }
        }

        public static class State {
            private static final String FIELD_AD_PLAYBACK_STATES = Util.intToStringMaxRadix(1);
            private final ImmutableMap<String, AdPlaybackState> adPlaybackStates;

            @VisibleForTesting
            public State(ImmutableMap<String, AdPlaybackState> immutableMap) {
                this.adPlaybackStates = immutableMap;
            }

            public static State fromBundle(Bundle bundle) {
                q0 q0Var = new q0(4);
                Bundle bundle2 = (Bundle) Assertions.checkNotNull(bundle.getBundle(FIELD_AD_PLAYBACK_STATES));
                for (String str : bundle2.keySet()) {
                    q0Var.b(str, AdPlaybackState.fromAdPlaybackState(str, AdPlaybackState.fromBundle((Bundle) Assertions.checkNotNull(bundle2.getBundle(str)))));
                }
                return new State(q0Var.a());
            }

            public boolean equals(@Nullable Object obj) {
                if (this == obj) {
                    return true;
                }
                if (obj instanceof State) {
                    return this.adPlaybackStates.equals(((State) obj).adPlaybackStates);
                }
                return false;
            }

            public int hashCode() {
                return this.adPlaybackStates.hashCode();
            }

            public Bundle toBundle() {
                Bundle bundle = new Bundle();
                Bundle bundle2 = new Bundle();
                v1 v1VarK = this.adPlaybackStates.entrySet().iterator();
                while (v1VarK.hasNext()) {
                    Map.Entry entry = (Map.Entry) v1VarK.next();
                    bundle2.putBundle((String) entry.getKey(), ((AdPlaybackState) entry.getValue()).toBundle());
                }
                bundle.putBundle(FIELD_AD_PLAYBACK_STATES, bundle2);
                return bundle;
            }
        }

        /* JADX INFO: Access modifiers changed from: private */
        public void addMediaSourceResources(ImaServerSideAdInsertionMediaSource imaServerSideAdInsertionMediaSource, StreamPlayer streamPlayer, com.google.ads.interactivemedia.v3.api.AdsLoader adsLoader) {
            this.mediaSourceResources.put(imaServerSideAdInsertionMediaSource.adsId, new MediaSourceResourceHolder(imaServerSideAdInsertionMediaSource, streamPlayer, adsLoader));
        }

        /* JADX INFO: Access modifiers changed from: private */
        public AdPlaybackState getAdPlaybackState(String str) {
            AdPlaybackState adPlaybackState = this.adPlaybackStateMap.get(str);
            return adPlaybackState != null ? adPlaybackState : AdPlaybackState.NONE;
        }

        /* JADX INFO: Access modifiers changed from: private */
        public void setAdPlaybackState(String str, AdPlaybackState adPlaybackState) {
            this.adPlaybackStateMap.put(str, adPlaybackState);
        }

        @UnstableApi
        public void focusSkipButton() {
            MediaSourceResourceHolder mediaSourceResourceHolder;
            Player player = this.player;
            if (player == null || player.getPlaybackState() == 1 || this.player.getPlaybackState() == 4 || this.player.getMediaItemCount() <= 0) {
                return;
            }
            Object adsId = this.player.getCurrentTimeline().getPeriod(this.player.getCurrentPeriodIndex(), new Timeline.Period()).getAdsId();
            if (!(adsId instanceof String) || (mediaSourceResourceHolder = this.mediaSourceResources.get(adsId)) == null || mediaSourceResourceHolder.imaServerSideAdInsertionMediaSource.streamManager == null) {
                return;
            }
            mediaSourceResourceHolder.imaServerSideAdInsertionMediaSource.streamManager.focus();
        }

        public State release() {
            for (MediaSourceResourceHolder mediaSourceResourceHolder : this.mediaSourceResources.values()) {
                mediaSourceResourceHolder.streamPlayer.release();
                mediaSourceResourceHolder.imaServerSideAdInsertionMediaSource.setStreamManager(null);
                mediaSourceResourceHolder.adsLoader.release();
            }
            State state = new State(ImmutableMap.b(this.adPlaybackStateMap));
            this.adPlaybackStateMap.clear();
            this.mediaSourceResources.clear();
            this.player = null;
            return state;
        }

        @UnstableApi
        public void replaceAdTagParameters(Map<String, String> map) {
            MediaSourceResourceHolder mediaSourceResourceHolder;
            Player player = this.player;
            if (player == null || player.getPlaybackState() == 1 || this.player.getPlaybackState() == 4 || this.player.getMediaItemCount() <= 0) {
                return;
            }
            Object adsId = this.player.getCurrentTimeline().getPeriod(this.player.getCurrentPeriodIndex(), new Timeline.Period()).getAdsId();
            if (!(adsId instanceof String) || (mediaSourceResourceHolder = this.mediaSourceResources.get(adsId)) == null || mediaSourceResourceHolder.imaServerSideAdInsertionMediaSource.streamManager == null) {
                return;
            }
            mediaSourceResourceHolder.imaServerSideAdInsertionMediaSource.streamManager.replaceAdTagParameters(map);
        }

        public void setPlayer(Player player) {
            this.player = player;
        }

        private AdsLoader(Context context, ImaUtil.ServerSideAdInsertionConfiguration serverSideAdInsertionConfiguration, State state) {
            this.context = context.getApplicationContext();
            this.configuration = serverSideAdInsertionConfiguration;
            this.mediaSourceResources = new HashMap();
            HashMap map = new HashMap();
            this.adPlaybackStateMap = map;
            map.putAll(state.adPlaybackStates);
        }
    }

    public final class ComponentListener implements AdEvent.AdEventListener, Player.Listener, ServerSideAdInsertionMediaSource.AdPlaybackStateUpdater {
        private final AdEvent.AdEventListener adEventListener;

        public ComponentListener(AdEvent.AdEventListener adEventListener) {
            this.adEventListener = adEventListener;
        }

        /* JADX INFO: Access modifiers changed from: private */
        public /* synthetic */ void lambda$onAdPlaybackStateUpdateRequested$0(Timeline timeline) {
            ImaServerSideAdInsertionMediaSource.this.setContentTimeline(timeline);
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener
        @MainThread
        public void onAdEvent(AdEvent adEvent) {
            this.adEventListener.onAdEvent(adEvent);
        }

        @Override // androidx.media3.exoplayer.source.ads.ServerSideAdInsertionMediaSource.AdPlaybackStateUpdater
        public boolean onAdPlaybackStateUpdateRequested(Timeline timeline) {
            ImaServerSideAdInsertionMediaSource.this.mainHandler.post(new a(this, timeline, 1));
            return !ImaServerSideAdInsertionMediaSource.this.isLiveStream || Objects.equals(ImaServerSideAdInsertionMediaSource.this.streamRequest.getFormat(), StreamRequest.StreamFormat.DASH);
        }

        /* JADX WARN: Multi-variable type inference failed */
        @Override // androidx.media3.common.Player.Listener
        public void onMetadata(Metadata metadata) {
            if (ImaServerSideAdInsertionMediaSource.isCurrentlyPlayingMediaPeriodFromThisSource(ImaServerSideAdInsertionMediaSource.this.player, ImaServerSideAdInsertionMediaSource.this.getMediaItem(), ImaServerSideAdInsertionMediaSource.this.adsId)) {
                for (int i10 = 0; i10 < metadata.length(); i10++) {
                    Metadata.Entry entry = metadata.get(i10);
                    if (entry instanceof o) {
                        o oVar = (o) entry;
                        if ("TXXX".equals(oVar.f25921a)) {
                            ImaServerSideAdInsertionMediaSource.this.streamPlayer.triggerUserTextReceived((String) oVar.f25933b.get(0));
                        }
                    } else if (entry instanceof c2.a) {
                        ImaServerSideAdInsertionMediaSource.this.streamPlayer.triggerUserTextReceived(new String(((c2.a) entry).f4865e));
                    }
                }
            }
        }

        @Override // androidx.media3.common.Player.Listener
        public void onPlaybackStateChanged(int i10) {
            if (i10 == 4 && ImaServerSideAdInsertionMediaSource.isCurrentlyPlayingMediaPeriodFromThisSource(ImaServerSideAdInsertionMediaSource.this.player, ImaServerSideAdInsertionMediaSource.this.getMediaItem(), ImaServerSideAdInsertionMediaSource.this.adsId)) {
                ImaServerSideAdInsertionMediaSource.this.streamPlayer.onContentCompleted();
            }
        }

        @Override // androidx.media3.common.Player.Listener
        public void onPositionDiscontinuity(Player.PositionInfo positionInfo, Player.PositionInfo positionInfo2, int i10) {
            int iIntValue;
            if (i10 == 0 || (ImaServerSideAdInsertionMediaSource.this.isLiveStream && i10 == 4)) {
                MediaItem mediaItem = ImaServerSideAdInsertionMediaSource.this.getMediaItem();
                if (mediaItem.equals(positionInfo.mediaItem) && !mediaItem.equals(positionInfo2.mediaItem)) {
                    ImaServerSideAdInsertionMediaSource.this.streamPlayer.onContentCompleted();
                }
                if (mediaItem.equals(positionInfo.mediaItem) && mediaItem.equals(positionInfo2.mediaItem) && ImaServerSideAdInsertionMediaSource.this.adsId.equals(ImaServerSideAdInsertionMediaSource.this.player.getCurrentTimeline().getPeriodByUid(Assertions.checkNotNull(positionInfo2.periodUid), new Timeline.Period()).getAdsId()) && (iIntValue = positionInfo.adGroupIndex) != -1) {
                    int iIntValue2 = positionInfo.adIndexInAdGroup;
                    Timeline currentTimeline = ImaServerSideAdInsertionMediaSource.this.player.getCurrentTimeline();
                    Timeline.Window window = currentTimeline.getWindow(positionInfo.mediaItemIndex, new Timeline.Window());
                    int i11 = window.lastPeriodIndex;
                    int i12 = window.firstPeriodIndex;
                    if (i11 > i12) {
                        if (i10 == 4) {
                            ImaServerSideAdInsertionMediaSource imaServerSideAdInsertionMediaSource = ImaServerSideAdInsertionMediaSource.this;
                            imaServerSideAdInsertionMediaSource.setAdPlaybackState(ImaUtil.handleAdPeriodRemovedFromTimeline(imaServerSideAdInsertionMediaSource.player.getCurrentPeriodIndex(), currentTimeline, ImaServerSideAdInsertionMediaSource.this.adPlaybackState));
                            return;
                        } else {
                            int i13 = positionInfo.periodIndex - i12;
                            Pair<Integer, Integer> adGroupAndIndexInLiveMultiPeriodTimeline = window.isLive() ? ImaUtil.getAdGroupAndIndexInLiveMultiPeriodTimeline(i13, ImaServerSideAdInsertionMediaSource.this.adPlaybackState, (Timeline) Assertions.checkNotNull(ImaServerSideAdInsertionMediaSource.this.contentTimeline)) : ImaUtil.getAdGroupAndIndexInVodMultiPeriodTimeline(i13, ImaServerSideAdInsertionMediaSource.this.adPlaybackState, (Timeline) Assertions.checkNotNull(ImaServerSideAdInsertionMediaSource.this.contentTimeline));
                            iIntValue = ((Integer) adGroupAndIndexInLiveMultiPeriodTimeline.first).intValue();
                            iIntValue2 = ((Integer) adGroupAndIndexInLiveMultiPeriodTimeline.second).intValue();
                        }
                    }
                    int i14 = ImaServerSideAdInsertionMediaSource.this.adPlaybackState.getAdGroup(iIntValue).states[iIntValue2];
                    if (i14 == 1 || i14 == 0) {
                        AdPlaybackState adPlaybackStateWithPlayedAd = ImaServerSideAdInsertionMediaSource.this.adPlaybackState.withPlayedAd(iIntValue, iIntValue2);
                        AdPlaybackState.AdGroup adGroup = adPlaybackStateWithPlayedAd.getAdGroup(iIntValue);
                        if (ImaServerSideAdInsertionMediaSource.this.isLiveStream && positionInfo2.adGroupIndex == -1) {
                            int[] iArr = adGroup.states;
                            if (iIntValue2 < iArr.length - 1) {
                                int i15 = iIntValue2 + 1;
                                if (iArr[i15] == 1) {
                                    Log.w(ImaServerSideAdInsertionMediaSource.TAG, "Detected late ad event. Regrouping trailing ads into separate ad group.");
                                    adPlaybackStateWithPlayedAd = ImaUtil.splitAdGroup(adGroup, iIntValue, i15, adPlaybackStateWithPlayedAd);
                                }
                            }
                        }
                        ImaServerSideAdInsertionMediaSource.this.setAdPlaybackState(adPlaybackStateWithPlayedAd);
                    }
                }
            }
        }

        @Override // androidx.media3.common.Player.Listener
        public void onVolumeChanged(float f10) {
            if (ImaServerSideAdInsertionMediaSource.isCurrentlyPlayingMediaPeriodFromThisSource(ImaServerSideAdInsertionMediaSource.this.player, ImaServerSideAdInsertionMediaSource.this.getMediaItem(), ImaServerSideAdInsertionMediaSource.this.adsId)) {
                ImaServerSideAdInsertionMediaSource.this.streamPlayer.onContentVolumeChanged((int) Math.floor(f10 * 100.0f));
            }
        }
    }

    public static final class Factory implements MediaSource.Factory {
        private final AdsLoader adsLoader;
        private final MediaSource.Factory contentMediaSourceFactory;

        public Factory(AdsLoader adsLoader, MediaSource.Factory factory) {
            this.adsLoader = adsLoader;
            this.contentMediaSourceFactory = factory;
        }

        @Override // androidx.media3.exoplayer.source.MediaSource.Factory
        @UnstableApi
        public MediaSource createMediaSource(MediaItem mediaItem) {
            Assertions.checkNotNull(mediaItem.localConfiguration);
            Player player = (Player) Assertions.checkNotNull(this.adsLoader.player);
            StreamRequest streamRequestCreateStreamRequest = ImaServerSideAdInsertionUriBuilder.createStreamRequest(((MediaItem.LocalConfiguration) Assertions.checkNotNull(mediaItem.localConfiguration)).uri);
            StreamPlayer streamPlayer = new StreamPlayer(player, mediaItem, streamRequestCreateStreamRequest);
            ImaSdkFactory imaSdkFactory = ImaSdkFactory.getInstance();
            com.google.ads.interactivemedia.v3.api.AdsLoader adsLoaderCreateAdsLoader = imaSdkFactory.createAdsLoader(this.adsLoader.context, this.adsLoader.configuration.imaSdkSettings, ImaServerSideAdInsertionMediaSource.createStreamDisplayContainer(imaSdkFactory, this.adsLoader.configuration, streamPlayer));
            ImaServerSideAdInsertionMediaSource imaServerSideAdInsertionMediaSource = new ImaServerSideAdInsertionMediaSource(player, mediaItem, streamRequestCreateStreamRequest, this.adsLoader, adsLoaderCreateAdsLoader, streamPlayer, this.contentMediaSourceFactory);
            this.adsLoader.addMediaSourceResources(imaServerSideAdInsertionMediaSource, streamPlayer, adsLoaderCreateAdsLoader);
            return imaServerSideAdInsertionMediaSource;
        }

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

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

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

    public class MultiPeriodLiveAdEventListener implements AdEvent.AdEventListener {
        private MultiPeriodLiveAdEventListener() {
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener
        public void onAdEvent(AdEvent adEvent) {
            if (Objects.equals(adEvent.getType(), AdEvent.AdEventType.LOADED) && ImaServerSideAdInsertionMediaSource.isCurrentlyPlayingMediaPeriodFromThisSource(ImaServerSideAdInsertionMediaSource.this.player, ImaServerSideAdInsertionMediaSource.this.getMediaItem(), ImaServerSideAdInsertionMediaSource.this.adsId)) {
                AdPodInfo adPodInfo = adEvent.getAd().getAdPodInfo();
                Timeline currentTimeline = ImaServerSideAdInsertionMediaSource.this.player.getCurrentTimeline();
                Timeline.Window window = new Timeline.Window();
                Timeline.Period period = new Timeline.Period();
                long adGroupDurationUsForLiveAdPeriodIndex = ImaUtil.getAdGroupDurationUsForLiveAdPeriodIndex(currentTimeline, adPodInfo, ImaServerSideAdInsertionMediaSource.this.player.getCurrentPeriodIndex(), window, period);
                long windowStartTimeUs = ImaUtil.getWindowStartTimeUs(window.windowStartTimeMs, window.positionInFirstPeriodUs) + period.positionInWindowUs;
                long jSecToUsRounded = period.durationUs;
                if (jSecToUsRounded == -9223372036854775807L) {
                    jSecToUsRounded = ImaUtil.secToUsRounded(adEvent.getAd().getDuration());
                }
                ImaServerSideAdInsertionMediaSource.this.setAdPlaybackState(ImaUtil.addLiveAdBreak(windowStartTimeUs, jSecToUsRounded, adPodInfo.getAdPosition(), adGroupDurationUsForLiveAdPeriodIndex, adPodInfo.getTotalAds(), ImaServerSideAdInsertionMediaSource.this.adPlaybackState));
            }
        }
    }

    public class SinglePeriodLiveAdEventListener implements AdEvent.AdEventListener {
        private SinglePeriodLiveAdEventListener() {
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener
        public void onAdEvent(AdEvent adEvent) {
            if (Objects.equals(adEvent.getType(), AdEvent.AdEventType.LOADED) && ImaServerSideAdInsertionMediaSource.isCurrentlyPlayingMediaPeriodFromThisSource(ImaServerSideAdInsertionMediaSource.this.player, ImaServerSideAdInsertionMediaSource.this.getMediaItem(), ImaServerSideAdInsertionMediaSource.this.adsId)) {
                AdPlaybackState adPlaybackState = ImaServerSideAdInsertionMediaSource.this.adPlaybackState;
                Timeline currentTimeline = ImaServerSideAdInsertionMediaSource.this.player.getCurrentTimeline();
                Timeline.Period period = new Timeline.Period();
                long j10 = currentTimeline.getPeriod(ImaServerSideAdInsertionMediaSource.this.player.getCurrentPeriodIndex(), period).positionInWindowUs;
                long adGroupTimeUs = ImaServerSideAdInsertionMediaSource.this.player.isPlayingAd() ? period.getAdGroupTimeUs(ImaServerSideAdInsertionMediaSource.this.player.getCurrentAdGroupIndex()) : Util.msToUs(ImaServerSideAdInsertionMediaSource.this.player.getContentPosition());
                Ad ad2 = adEvent.getAd();
                AdPodInfo adPodInfo = ad2.getAdPodInfo();
                long j11 = adGroupTimeUs - j10;
                long jSecToUsRounded = ImaUtil.secToUsRounded(ad2.getDuration());
                int adPosition = adPodInfo.getAdPosition();
                long jSecToUsRounded2 = ImaUtil.secToUsRounded(adPodInfo.getMaxDuration());
                int totalAds = adPodInfo.getTotalAds();
                if (adPlaybackState.equals(AdPlaybackState.NONE)) {
                    adPlaybackState = new AdPlaybackState(ImaServerSideAdInsertionMediaSource.this.adsId, new long[0]);
                }
                ImaServerSideAdInsertionMediaSource.this.setAdPlaybackState(ImaUtil.addLiveAdBreak(j11, jSecToUsRounded, adPosition, jSecToUsRounded2, totalAds, adPlaybackState));
            }
        }
    }

    @UnstableApi
    public interface StreamEventListener {
        void onStreamIdChanged(MediaItem mediaItem, String str);
    }

    public static class StreamManagerLoadable implements Loader.Loadable, AdsLoader.AdsLoadedListener, AdErrorEvent.AdErrorListener {

        @Nullable
        private final AdErrorEvent.AdErrorListener adErrorListener;
        private final com.google.ads.interactivemedia.v3.api.AdsLoader adsLoader;
        private volatile boolean cancelled;
        private final ConditionVariable conditionVariable;

        @Nullable
        private volatile Uri contentUri;
        private volatile boolean error;
        private volatile int errorCode;

        @Nullable
        private volatile String errorMessage;
        private final ImaServerSideAdInsertionMediaSource imaServerSideAdInsertionMediaSource;
        private final StreamRequest request;
        private final StreamPlayer streamPlayer;

        /* JADX INFO: Access modifiers changed from: private */
        public /* synthetic */ void lambda$load$0(String str, List list) {
            this.contentUri = Uri.parse(str);
            this.conditionVariable.open();
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Loadable
        public void cancelLoad() {
            this.cancelled = true;
        }

        @Nullable
        public Uri getContentUri() {
            return this.contentUri;
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Loadable
        public void load() throws IOException {
            try {
                this.streamPlayer.setStreamLoadListener(new StreamPlayer.StreamLoadListener() { // from class: androidx.media3.exoplayer.ima.d
                    @Override // androidx.media3.exoplayer.ima.ImaServerSideAdInsertionMediaSource.StreamPlayer.StreamLoadListener
                    public final void onLoadStream(String str, List list) {
                        this.f3064a.lambda$load$0(str, list);
                    }
                });
                AdErrorEvent.AdErrorListener adErrorListener = this.adErrorListener;
                if (adErrorListener != null) {
                    this.adsLoader.addAdErrorListener(adErrorListener);
                }
                this.adsLoader.addAdsLoadedListener(this);
                this.adsLoader.addAdErrorListener(this);
                this.adsLoader.requestStream(this.request);
                while (this.contentUri == null && !this.cancelled && !this.error) {
                    try {
                        this.conditionVariable.block();
                    } catch (InterruptedException unused) {
                    }
                }
                if (this.error && this.contentUri == null) {
                    throw new IOException(this.errorMessage + " [errorCode: " + this.errorCode + "]");
                }
            } finally {
                this.adsLoader.removeAdsLoadedListener(this);
                this.adsLoader.removeAdErrorListener(this);
                AdErrorEvent.AdErrorListener adErrorListener2 = this.adErrorListener;
                if (adErrorListener2 != null) {
                    this.adsLoader.removeAdErrorListener(adErrorListener2);
                }
            }
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdErrorEvent.AdErrorListener
        @MainThread
        public void onAdError(AdErrorEvent adErrorEvent) {
            this.error = true;
            if (adErrorEvent.getError() != null) {
                String message = adErrorEvent.getError().getMessage();
                if (message != null) {
                    this.errorMessage = message.replace('\n', ' ');
                }
                this.errorCode = adErrorEvent.getError().getErrorCodeNumber();
            }
            this.conditionVariable.open();
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdsLoader.AdsLoadedListener
        @MainThread
        public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) {
            StreamManager streamManager = adsManagerLoadedEvent.getStreamManager();
            if (streamManager != null) {
                this.imaServerSideAdInsertionMediaSource.setStreamManager(streamManager);
                return;
            }
            this.error = true;
            this.errorMessage = "streamManager is null after ads manager has been loaded";
            this.conditionVariable.open();
        }

        private StreamManagerLoadable(com.google.ads.interactivemedia.v3.api.AdsLoader adsLoader, ImaServerSideAdInsertionMediaSource imaServerSideAdInsertionMediaSource, StreamRequest streamRequest, StreamPlayer streamPlayer, @Nullable AdErrorEvent.AdErrorListener adErrorListener) {
            this.adsLoader = adsLoader;
            this.imaServerSideAdInsertionMediaSource = imaServerSideAdInsertionMediaSource;
            this.request = streamRequest;
            this.streamPlayer = streamPlayer;
            this.adErrorListener = adErrorListener;
            this.conditionVariable = new ConditionVariable();
            this.errorCode = -1;
        }
    }

    public final class StreamManagerLoadableCallback implements Loader.Callback<StreamManagerLoadable> {
        private StreamManagerLoadableCallback() {
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Callback
        public void onLoadCanceled(StreamManagerLoadable streamManagerLoadable, long j10, long j11, boolean z10) {
            Assertions.checkState(z10);
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Callback
        public void onLoadCompleted(StreamManagerLoadable streamManagerLoadable, long j10, long j11) {
            ImaServerSideAdInsertionMediaSource.this.setContentUri((Uri) Assertions.checkNotNull(streamManagerLoadable.getContentUri()));
        }

        @Override // androidx.media3.exoplayer.upstream.Loader.Callback
        public Loader.LoadErrorAction onLoadError(StreamManagerLoadable streamManagerLoadable, long j10, long j11, IOException iOException, int i10) {
            ImaServerSideAdInsertionMediaSource.this.loadError = iOException;
            return Loader.DONT_RETRY;
        }
    }

    public static final class StreamPlayer implements VideoStreamPlayer {
        private ImmutableMap<Object, AdPlaybackState> adPlaybackStates;

        @Nullable
        private Object adsId;
        private final List<VideoStreamPlayer.VideoStreamPlayerCallback> callbacks;

        @Nullable
        private Timeline contentTimeline;
        private final boolean isDashStream;
        private final MediaItem mediaItem;
        private final Timeline.Period period;
        private final Player player;

        @Nullable
        private StreamLoadListener streamLoadListener;
        private final Timeline.Window window;

        public interface StreamLoadListener {
            void onLoadStream(String str, List<HashMap<String, String>> list);
        }

        public StreamPlayer(Player player, MediaItem mediaItem, StreamRequest streamRequest) {
            this.player = player;
            this.mediaItem = mediaItem;
            this.isDashStream = streamRequest.getFormat() == StreamRequest.StreamFormat.DASH;
            this.callbacks = new ArrayList(1);
            this.adPlaybackStates = ImmutableMap.g();
            this.window = new Timeline.Window();
            this.period = new Timeline.Period();
        }

        /* JADX INFO: Access modifiers changed from: private */
        public void triggerUserTextReceived(String str) {
            Iterator<VideoStreamPlayer.VideoStreamPlayerCallback> it = this.callbacks.iterator();
            while (it.hasNext()) {
                it.next().onUserTextReceived(str);
            }
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoStreamPlayer
        public void addCallback(VideoStreamPlayer.VideoStreamPlayerCallback videoStreamPlayerCallback) {
            this.callbacks.add(videoStreamPlayerCallback);
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider
        public VideoProgressUpdate getContentProgress() {
            long contentPosition;
            long jUsToMs;
            if (!ImaServerSideAdInsertionMediaSource.isCurrentlyPlayingMediaPeriodFromThisSource(this.player, this.mediaItem, this.adsId)) {
                return VideoProgressUpdate.VIDEO_TIME_NOT_READY;
            }
            if (this.adPlaybackStates.isEmpty()) {
                return new VideoProgressUpdate(0L, -9223372036854775807L);
            }
            Timeline currentTimeline = this.player.getCurrentTimeline();
            int currentPeriodIndex = this.player.getCurrentPeriodIndex();
            currentTimeline.getPeriod(currentPeriodIndex, this.period, true);
            currentTimeline.getWindow(this.player.getCurrentMediaItemIndex(), this.window);
            if (!this.isDashStream || !this.window.isLive()) {
                Timeline.Period period = ((Timeline) Assertions.checkNotNull(this.contentTimeline)).getPeriod(currentPeriodIndex - this.window.firstPeriodIndex, new Timeline.Period(), true);
                long jUsToMs2 = Util.usToMs(ServerSideAdInsertionUtil.getStreamPositionUs(this.player, Assertions.checkNotNull(((AdPlaybackState) Assertions.checkNotNull((AdPlaybackState) this.adPlaybackStates.get(period.uid))).adsId)));
                Timeline.Window window = this.window;
                long j10 = window.windowStartTimeMs;
                if (j10 != -9223372036854775807L) {
                    jUsToMs = this.period.getPositionInWindowMs() + j10;
                } else if (currentPeriodIndex > window.firstPeriodIndex) {
                    ((Timeline) Assertions.checkNotNull(this.contentTimeline)).getPeriod((currentPeriodIndex - this.window.firstPeriodIndex) - 1, period, true);
                    jUsToMs = Util.usToMs(period.positionInWindowUs + period.durationUs);
                } else {
                    contentPosition = jUsToMs2;
                }
                contentPosition = jUsToMs + jUsToMs2;
            } else if (this.player.isPlayingAd()) {
                contentPosition = this.player.getCurrentPosition() + Util.usToMs(this.period.positionInWindowUs) + this.window.windowStartTimeMs;
            } else {
                contentPosition = this.window.windowStartTimeMs + this.player.getContentPosition();
            }
            return new VideoProgressUpdate(contentPosition, ((Timeline) Assertions.checkNotNull(this.contentTimeline)).getWindow(0, this.window).getDurationMs());
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VolumeProvider
        public int getVolume() {
            return (int) Math.floor(this.player.getVolume() * 100.0f);
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoStreamPlayer
        public void loadUrl(String str, List<HashMap<String, String>> list) {
            StreamLoadListener streamLoadListener = this.streamLoadListener;
            if (streamLoadListener != null) {
                streamLoadListener.onLoadStream(str, list);
            }
        }

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

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

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

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

        public void onContentCompleted() {
            Iterator<VideoStreamPlayer.VideoStreamPlayerCallback> it = this.callbacks.iterator();
            while (it.hasNext()) {
                it.next().onContentComplete();
            }
        }

        public void onContentVolumeChanged(int i10) {
            Iterator<VideoStreamPlayer.VideoStreamPlayerCallback> it = this.callbacks.iterator();
            while (it.hasNext()) {
                it.next().onVolumeChanged(i10);
            }
        }

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

        public void release() {
            this.callbacks.clear();
            this.adsId = null;
            this.adPlaybackStates = ImmutableMap.g();
            this.contentTimeline = null;
            this.streamLoadListener = null;
        }

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoStreamPlayer
        public void removeCallback(VideoStreamPlayer.VideoStreamPlayerCallback videoStreamPlayerCallback) {
            this.callbacks.remove(videoStreamPlayerCallback);
        }

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

        @Override // com.google.ads.interactivemedia.v3.api.player.VideoStreamPlayer
        public void seek(long j10) {
        }

        public void setAdPlaybackStates(Object obj, ImmutableMap<Object, AdPlaybackState> immutableMap, Timeline timeline) {
            this.adsId = obj;
            this.adPlaybackStates = immutableMap;
            this.contentTimeline = timeline;
        }

        public void setStreamLoadListener(StreamLoadListener streamLoadListener) {
            this.streamLoadListener = (StreamLoadListener) Assertions.checkNotNull(streamLoadListener);
        }
    }

    public class VodAdEventListener implements AdEvent.AdEventListener {
        private VodAdEventListener() {
        }

        @Override // com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener
        public void onAdEvent(AdEvent adEvent) {
            AdPlaybackState vodAdGroupPlaceholders = ImaServerSideAdInsertionMediaSource.this.adPlaybackState;
            int i10 = AnonymousClass2.$SwitchMap$com$google$ads$interactivemedia$v3$api$AdEvent$AdEventType[adEvent.getType().ordinal()];
            if (i10 != 1) {
                if (i10 == 2) {
                    vodAdGroupPlaceholders = ImaServerSideAdInsertionMediaSource.setVodAdInPlaceholder(adEvent.getAd(), vodAdGroupPlaceholders);
                } else if (i10 == 3) {
                    vodAdGroupPlaceholders = ImaServerSideAdInsertionMediaSource.skipAd(adEvent.getAd(), vodAdGroupPlaceholders);
                }
            } else if (vodAdGroupPlaceholders.equals(AdPlaybackState.NONE)) {
                vodAdGroupPlaceholders = ImaServerSideAdInsertionMediaSource.setVodAdGroupPlaceholders(((StreamManager) Assertions.checkNotNull(ImaServerSideAdInsertionMediaSource.this.streamManager)).getCuePoints(), new AdPlaybackState(ImaServerSideAdInsertionMediaSource.this.adsId, new long[0]));
            }
            ImaServerSideAdInsertionMediaSource.this.setAdPlaybackState(vodAdGroupPlaceholders);
        }
    }

    private static void assertSingleInstanceInPlaylist(Player player) {
        int i10 = 0;
        for (int i11 = 0; i11 < player.getMediaItemCount(); i11++) {
            MediaItem mediaItemAt = player.getMediaItemAt(i11);
            MediaItem.LocalConfiguration localConfiguration = mediaItemAt.localConfiguration;
            if (localConfiguration != null && C.SSAI_SCHEME.equals(localConfiguration.uri.getScheme()) && "dai.google.com".equals(mediaItemAt.localConfiguration.uri.getAuthority()) && (i10 = i10 + 1) > 1) {
                throw new IllegalStateException("Multiple IMA server side ad insertion sources not supported.");
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static StreamDisplayContainer createStreamDisplayContainer(ImaSdkFactory imaSdkFactory, ImaUtil.ServerSideAdInsertionConfiguration serverSideAdInsertionConfiguration, StreamPlayer streamPlayer) {
        StreamDisplayContainer streamDisplayContainerCreateStreamDisplayContainer = ImaSdkFactory.createStreamDisplayContainer((ViewGroup) Assertions.checkNotNull(serverSideAdInsertionConfiguration.adViewProvider.getAdViewGroup()), streamPlayer);
        streamDisplayContainerCreateStreamDisplayContainer.setCompanionSlots(serverSideAdInsertionConfiguration.companionAdSlots);
        registerFriendlyObstructions(imaSdkFactory, streamDisplayContainerCreateStreamDisplayContainer, serverSideAdInsertionConfiguration.adViewProvider);
        return streamDisplayContainerCreateStreamDisplayContainer;
    }

    private static long getAdDuration(double d10, double d11) {
        return Util.msToUs(ImaUtil.secToMsRounded(d11 - d10));
    }

    private static int getAdGroupIndexFromAdPodInfo(AdPodInfo adPodInfo, AdPlaybackState adPlaybackState) {
        int podIndex = adPodInfo.getPodIndex();
        return podIndex == -1 ? adPlaybackState.adGroupCount - 1 : adPlaybackState.getAdGroup(0).timeUs == 0 ? podIndex : podIndex - 1;
    }

    @MainThread
    private void invalidateServerSideAdInsertionAdPlaybackState() {
        Timeline timeline;
        if (this.adPlaybackState.equals(AdPlaybackState.NONE) || (timeline = this.contentTimeline) == null || this.serverSideAdInsertionMediaSource == null) {
            return;
        }
        Timeline timeline2 = (Timeline) Assertions.checkNotNull(timeline);
        ImmutableMap<Object, AdPlaybackState> immutableMapSplitAdPlaybackStateForPeriods = Objects.equals(this.streamRequest.getFormat(), StreamRequest.StreamFormat.DASH) ? ImaUtil.splitAdPlaybackStateForPeriods(this.adPlaybackState, timeline2) : ImmutableMap.i(Assertions.checkNotNull(timeline2.getPeriod(timeline2.getWindow(0, new Timeline.Window()).firstPeriodIndex, new Timeline.Period(), true).uid), this.adPlaybackState);
        this.streamPlayer.setAdPlaybackStates(this.adsId, immutableMapSplitAdPlaybackStateForPeriods, timeline2);
        ((ServerSideAdInsertionMediaSource) Assertions.checkNotNull(this.serverSideAdInsertionMediaSource)).setAdPlaybackStates(immutableMapSplitAdPlaybackStateForPeriods, timeline2);
        if (this.isLiveStream) {
            return;
        }
        this.adsLoader.setAdPlaybackState(this.adsId, this.adPlaybackState);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static boolean isCurrentlyPlayingMediaPeriodFromThisSource(Player player, MediaItem mediaItem, @Nullable Object obj) {
        if (player.getPlaybackState() == 1 || player.getMediaItemCount() == 0) {
            return false;
        }
        Timeline.Period period = new Timeline.Period();
        player.getCurrentTimeline().getPeriod(player.getCurrentPeriodIndex(), period);
        return (period.isPlaceholder && mediaItem.equals(player.getCurrentMediaItem())) || (obj != null && obj.equals(period.getAdsId()));
    }

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

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$releaseSourceInternal$1() {
        this.player.removeListener(this.componentListener);
        setStreamManager(null);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$setContentUri$2() {
        setAdPlaybackState(new AdPlaybackState(this.adsId, new long[0]).withLivePostrollPlaceholderAppended(true));
    }

    private static void registerFriendlyObstructions(ImaSdkFactory imaSdkFactory, StreamDisplayContainer streamDisplayContainer, AdViewProvider adViewProvider) {
        for (int i10 = 0; i10 < adViewProvider.getAdOverlayInfos().size(); i10++) {
            AdOverlayInfo adOverlayInfo = adViewProvider.getAdOverlayInfos().get(i10);
            View view = adOverlayInfo.view;
            FriendlyObstructionPurpose friendlyObstructionPurpose = ImaUtil.getFriendlyObstructionPurpose(adOverlayInfo.purpose);
            String str = adOverlayInfo.reasonDetail;
            if (str == null) {
                str = "Unknown reason";
            }
            streamDisplayContainer.registerFriendlyObstruction(imaSdkFactory.createFriendlyObstruction(view, friendlyObstructionPurpose, str));
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    @MainThread
    public void setAdPlaybackState(AdPlaybackState adPlaybackState) {
        if (adPlaybackState.equals(this.adPlaybackState)) {
            return;
        }
        this.adPlaybackState = adPlaybackState;
        invalidateServerSideAdInsertionAdPlaybackState();
    }

    /* JADX INFO: Access modifiers changed from: private */
    @MainThread
    public void setContentTimeline(Timeline timeline) {
        if (timeline.equals(this.contentTimeline)) {
            return;
        }
        if (this.isLiveStream && Objects.equals(this.streamRequest.getFormat(), StreamRequest.StreamFormat.DASH)) {
            this.adPlaybackState = ImaUtil.maybeCorrectPreviouslyUnknownAdDurations(timeline, this.adPlaybackState);
        }
        this.contentTimeline = timeline;
        invalidateServerSideAdInsertionAdPlaybackState();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void setContentUri(Uri uri) {
        if (this.serverSideAdInsertionMediaSource == null) {
            MediaItem mediaItem = getMediaItem();
            ServerSideAdInsertionMediaSource serverSideAdInsertionMediaSource = new ServerSideAdInsertionMediaSource(this.contentMediaSourceFactory.createMediaSource(new MediaItem.Builder().setUri(uri).setDrmConfiguration(((MediaItem.LocalConfiguration) Assertions.checkNotNull(mediaItem.localConfiguration)).drmConfiguration).setLiveConfiguration(mediaItem.liveConfiguration).setCustomCacheKey(mediaItem.localConfiguration.customCacheKey).setStreamKeys(mediaItem.localConfiguration.streamKeys).build()), this.componentListener);
            this.serverSideAdInsertionMediaSource = serverSideAdInsertionMediaSource;
            if (this.isLiveStream) {
                this.mainHandler.post(new c(this, 1));
            }
            prepareChildSource(null, serverSideAdInsertionMediaSource);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    @MainThread
    public void setStreamManager(@Nullable StreamManager streamManager) {
        StreamManager streamManager2 = this.streamManager;
        if (streamManager2 == streamManager) {
            return;
        }
        if (streamManager2 != null) {
            AdEvent.AdEventListener adEventListener = this.applicationAdEventListener;
            if (adEventListener != null) {
                streamManager2.removeAdEventListener(adEventListener);
            }
            AdErrorEvent.AdErrorListener adErrorListener = this.applicationAdErrorListener;
            if (adErrorListener != null) {
                this.streamManager.removeAdErrorListener(adErrorListener);
            }
            this.streamManager.removeAdEventListener(this.componentListener);
            this.streamManager.destroy();
            this.streamId = null;
        }
        this.streamManager = streamManager;
        if (streamManager != null) {
            String streamId = streamManager.getStreamId();
            if (!Objects.equals(this.streamId, streamId)) {
                this.streamId = streamId;
                this.streamEventListener.onStreamIdChanged(getMediaItem(), streamId);
            }
            streamManager.addAdEventListener(this.componentListener);
            AdEvent.AdEventListener adEventListener2 = this.applicationAdEventListener;
            if (adEventListener2 != null) {
                streamManager.addAdEventListener(adEventListener2);
            }
            AdErrorEvent.AdErrorListener adErrorListener2 = this.applicationAdErrorListener;
            if (adErrorListener2 != null) {
                streamManager.addAdErrorListener(adErrorListener2);
            }
            AdsRenderingSettings adsRenderingSettingsCreateAdsRenderingSettings = ImaSdkFactory.getInstance().createAdsRenderingSettings();
            adsRenderingSettingsCreateAdsRenderingSettings.setLoadVideoTimeout(this.loadVideoTimeoutMs);
            adsRenderingSettingsCreateAdsRenderingSettings.setFocusSkipButtonWhenAvailable(this.adsLoader.configuration.focusSkipButtonWhenAvailable);
            streamManager.init(adsRenderingSettingsCreateAdsRenderingSettings);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static AdPlaybackState setVodAdGroupPlaceholders(List<CuePoint> list, AdPlaybackState adPlaybackState) {
        AdPlaybackState adPlaybackStateAddAdGroupToAdPlaybackState = adPlaybackState;
        for (int i10 = 0; i10 < list.size(); i10++) {
            CuePoint cuePoint = list.get(i10);
            adPlaybackStateAddAdGroupToAdPlaybackState = ServerSideAdInsertionUtil.addAdGroupToAdPlaybackState(adPlaybackStateAddAdGroupToAdPlaybackState, Util.msToUs(ImaUtil.secToMsRounded(cuePoint.getStartTime())), 0L, getAdDuration(cuePoint.getStartTime(), cuePoint.getEndTime()));
        }
        return adPlaybackStateAddAdGroupToAdPlaybackState;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static AdPlaybackState setVodAdInPlaceholder(Ad ad2, AdPlaybackState adPlaybackState) {
        AdPodInfo adPodInfo = ad2.getAdPodInfo();
        int adGroupIndexFromAdPodInfo = getAdGroupIndexFromAdPodInfo(adPodInfo, adPlaybackState);
        AdPlaybackState.AdGroup adGroup = adPlaybackState.getAdGroup(adGroupIndexFromAdPodInfo);
        int adPosition = adPodInfo.getAdPosition() - 1;
        return adGroup.count < adPodInfo.getTotalAds() ? ImaUtil.expandAdGroupPlaceholder(adGroupIndexFromAdPodInfo, Util.msToUs(ImaUtil.secToMsRounded(adPodInfo.getMaxDuration())), adPosition, Util.msToUs(ImaUtil.secToMsRounded(ad2.getDuration())), adPodInfo.getTotalAds(), adPlaybackState) : adPosition < adGroup.count + (-1) ? ImaUtil.updateAdDurationInAdGroup(adGroupIndexFromAdPodInfo, adPosition, Util.msToUs(ImaUtil.secToMsRounded(ad2.getDuration())), adPlaybackState) : adPlaybackState;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static AdPlaybackState skipAd(Ad ad2, AdPlaybackState adPlaybackState) {
        return adPlaybackState.withSkippedAd(getAdGroupIndexFromAdPodInfo(ad2.getAdPodInfo(), adPlaybackState), r1.getAdPosition() - 1);
    }

    @Override // androidx.media3.exoplayer.source.MediaSource
    @UnstableApi
    public boolean canUpdateMediaItem(MediaItem mediaItem) {
        MediaItem mediaItem2 = getMediaItem();
        MediaItem.LocalConfiguration localConfiguration = (MediaItem.LocalConfiguration) Assertions.checkNotNull(mediaItem2.localConfiguration);
        MediaItem.LocalConfiguration localConfiguration2 = mediaItem.localConfiguration;
        return localConfiguration2 != null && localConfiguration2.uri.equals(localConfiguration.uri) && localConfiguration2.streamKeys.equals(localConfiguration.streamKeys) && Objects.equals(localConfiguration2.customCacheKey, localConfiguration.customCacheKey) && Objects.equals(localConfiguration2.drmConfiguration, localConfiguration.drmConfiguration) && mediaItem2.liveConfiguration.equals(mediaItem.liveConfiguration);
    }

    @Override // androidx.media3.exoplayer.source.MediaSource
    @UnstableApi
    public MediaPeriod createPeriod(MediaSource.MediaPeriodId mediaPeriodId, Allocator allocator, long j10) {
        return ((ServerSideAdInsertionMediaSource) Assertions.checkNotNull(this.serverSideAdInsertionMediaSource)).createPeriod(mediaPeriodId, allocator, j10);
    }

    @Override // androidx.media3.exoplayer.source.MediaSource
    @UnstableApi
    public synchronized MediaItem getMediaItem() {
        return this.mediaItem;
    }

    @Override // androidx.media3.exoplayer.source.CompositeMediaSource, androidx.media3.exoplayer.source.MediaSource
    @UnstableApi
    public void maybeThrowSourceInfoRefreshError() throws IOException {
        super.maybeThrowSourceInfoRefreshError();
        IOException iOException = this.loadError;
        if (iOException == null) {
            return;
        }
        this.loadError = null;
        throw iOException;
    }

    @Override // androidx.media3.exoplayer.source.CompositeMediaSource, androidx.media3.exoplayer.source.BaseMediaSource
    @UnstableApi
    public void prepareSourceInternal(@Nullable TransferListener transferListener) {
        this.mainHandler.post(new c(this, 2));
        super.prepareSourceInternal(transferListener);
        if (this.loader == null) {
            Loader loader = new Loader("ImaServerSideAdInsertionMediaSource");
            this.player.addListener(this.componentListener);
            loader.startLoading(new StreamManagerLoadable(this.sdkAdsLoader, this, this.streamRequest, this.streamPlayer, this.applicationAdErrorListener), new StreamManagerLoadableCallback(), 0);
            this.loader = loader;
        }
    }

    @Override // androidx.media3.exoplayer.source.MediaSource
    @UnstableApi
    public void releasePeriod(MediaPeriod mediaPeriod) {
        ((ServerSideAdInsertionMediaSource) Assertions.checkNotNull(this.serverSideAdInsertionMediaSource)).releasePeriod(mediaPeriod);
    }

    @Override // androidx.media3.exoplayer.source.CompositeMediaSource, androidx.media3.exoplayer.source.BaseMediaSource
    @UnstableApi
    public void releaseSourceInternal() {
        super.releaseSourceInternal();
        Loader loader = this.loader;
        if (loader != null) {
            loader.release();
            this.mainHandler.post(new c(this, 0));
            this.loader = null;
        }
        this.contentTimeline = null;
        this.serverSideAdInsertionMediaSource = null;
    }

    @Override // androidx.media3.exoplayer.source.MediaSource
    @UnstableApi
    public synchronized void updateMediaItem(MediaItem mediaItem) {
        this.mediaItem = mediaItem;
    }

    private ImaServerSideAdInsertionMediaSource(Player player, MediaItem mediaItem, StreamRequest streamRequest, AdsLoader adsLoader, com.google.ads.interactivemedia.v3.api.AdsLoader adsLoader2, StreamPlayer streamPlayer, MediaSource.Factory factory) {
        this.player = player;
        this.mediaItem = mediaItem;
        this.streamRequest = streamRequest;
        this.adsLoader = adsLoader;
        this.sdkAdsLoader = adsLoader2;
        this.streamPlayer = streamPlayer;
        this.contentMediaSourceFactory = factory;
        this.streamEventListener = adsLoader.configuration.streamEventListener;
        this.applicationAdEventListener = adsLoader.configuration.applicationAdEventListener;
        this.applicationAdErrorListener = adsLoader.configuration.applicationAdErrorListener;
        Assertions.checkArgument(player.getApplicationLooper() == Looper.getMainLooper());
        this.mainHandler = new Handler(Looper.getMainLooper());
        Uri uri = ((MediaItem.LocalConfiguration) Assertions.checkNotNull(mediaItem.localConfiguration)).uri;
        boolean zIsLiveStream = ImaServerSideAdInsertionUriBuilder.isLiveStream(uri);
        this.isLiveStream = zIsLiveStream;
        String adsId = ImaServerSideAdInsertionUriBuilder.getAdsId(uri);
        this.adsId = adsId;
        this.loadVideoTimeoutMs = ImaServerSideAdInsertionUriBuilder.getLoadVideoTimeoutMs(uri);
        this.componentListener = new ComponentListener(zIsLiveStream ? Objects.equals(ImaServerSideAdInsertionUriBuilder.createStreamRequest(uri).getFormat(), StreamRequest.StreamFormat.DASH) ? new MultiPeriodLiveAdEventListener() : new SinglePeriodLiveAdEventListener() : new VodAdEventListener());
        this.adPlaybackState = adsLoader.getAdPlaybackState(adsId);
    }

    @Override // androidx.media3.exoplayer.source.CompositeMediaSource
    @UnstableApi
    public void lambda$prepareChildSource$0(Void r12, MediaSource mediaSource, final Timeline timeline) {
        final MediaItem mediaItem = getMediaItem();
        refreshSourceInfo(new ForwardingTimeline(timeline) { // from class: androidx.media3.exoplayer.ima.ImaServerSideAdInsertionMediaSource.1
            @Override // androidx.media3.exoplayer.source.ForwardingTimeline, androidx.media3.common.Timeline
            public Timeline.Window getWindow(int i10, Timeline.Window window, long j10) {
                timeline.getWindow(i10, window, j10);
                window.mediaItem = mediaItem;
                return window;
            }
        });
    }
}
