package androidx.media3.session;

import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaMetadata;
import androidx.media3.common.Player;
import androidx.media3.common.util.Assertions;
import androidx.media3.common.util.Log;
import androidx.media3.common.util.Util;
import androidx.media3.session.MediaLibraryService;
import androidx.media3.session.MediaSession;
import androidx.media3.session.MediaSessionImpl;
import androidx.media3.session.legacy.MediaSessionCompat;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.UnmodifiableIterator;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/* JADX INFO: loaded from: classes.dex */
class MediaLibrarySessionImpl extends MediaSessionImpl {
    private static final String RECENT_LIBRARY_ROOT_MEDIA_ID = "androidx.media3.session.recent.root";
    private final MediaLibraryService.MediaLibrarySession.Callback callback;
    private final HashMultimap<MediaSession.ControllerCb, String> controllerToSubscribedParentIds;
    private final MediaLibraryService.MediaLibrarySession instance;
    private final int libraryErrorReplicationMode;
    private final HashMultimap<String, MediaSession.ControllerInfo> parentIdToSubscribedControllers;

    public MediaLibrarySessionImpl(MediaLibraryService.MediaLibrarySession mediaLibrarySession, Context context, String str, Player player, @Nullable PendingIntent pendingIntent, ImmutableList<CommandButton> immutableList, ImmutableList<CommandButton> immutableList2, ImmutableList<CommandButton> immutableList3, MediaLibraryService.MediaLibrarySession.Callback callback, Bundle bundle, Bundle bundle2, androidx.media3.common.util.BitmapLoader bitmapLoader, boolean z2, boolean z3, int i2) {
        super(mediaLibrarySession, context, str, player, pendingIntent, immutableList, immutableList2, immutableList3, callback, bundle, bundle2, bitmapLoader, z2, z3);
        this.instance = mediaLibrarySession;
        this.callback = callback;
        this.libraryErrorReplicationMode = i2;
        this.parentIdToSubscribedControllers = HashMultimap.create();
        this.controllerToSubscribedParentIds = HashMultimap.create();
    }

    private ListenableFuture getRecentMediaItemAtDeviceBootTime(MediaSession.ControllerInfo controllerInfo, @Nullable final MediaLibraryService.LibraryParams libraryParams) {
        final SettableFuture settableFutureCreate = SettableFuture.create();
        if (isMediaNotificationControllerConnected()) {
            controllerInfo = (MediaSession.ControllerInfo) Assertions.checkNotNull(getMediaNotificationControllerInfo());
        }
        Futures.addCallback(this.callback.onPlaybackResumption(this.instance, controllerInfo), new FutureCallback<MediaSession.MediaItemsWithStartPosition>() { // from class: androidx.media3.session.MediaLibrarySessionImpl.1
            public void onFailure(Throwable th) {
                settableFutureCreate.set(LibraryResult.ofError(-1, libraryParams));
                Log.e(MediaSessionImpl.TAG, "Failed fetching recent media item at boot time: " + th.getMessage(), th);
            }

            public void onSuccess(MediaSession.MediaItemsWithStartPosition mediaItemsWithStartPosition) {
                if (mediaItemsWithStartPosition.mediaItems.isEmpty()) {
                    settableFutureCreate.set(LibraryResult.ofError(-2, libraryParams));
                } else {
                    settableFutureCreate.set(LibraryResult.ofItemList(ImmutableList.of((MediaItem) mediaItemsWithStartPosition.mediaItems.get(Math.max(0, Math.min(mediaItemsWithStartPosition.startIndex, mediaItemsWithStartPosition.mediaItems.size() - 1)))), libraryParams));
                }
            }
        }, MoreExecutors.directExecutor());
        return settableFutureCreate;
    }

    private boolean isReplicationErrorCode(int i2) {
        return i2 == -102 || i2 == -105;
    }

    private boolean isSubscribed(MediaSession.ControllerCb controllerCb, String str) {
        return this.controllerToSubscribedParentIds.containsEntry(controllerCb, str);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$notifyChildrenChanged$4(String str, int i2, MediaLibraryService.LibraryParams libraryParams, MediaSession.ControllerCb controllerCb, int i3) throws RemoteException {
        if (isSubscribed(controllerCb, str)) {
            controllerCb.onChildrenChanged(i3, str, i2, libraryParams);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$onGetChildrenOnHandler$0(ListenableFuture listenableFuture, MediaSession.ControllerInfo controllerInfo, int i2) {
        LibraryResult<?> libraryResult = (LibraryResult) tryGetFutureResult(listenableFuture);
        if (libraryResult != null) {
            maybeUpdateLegacyErrorState(controllerInfo, libraryResult);
            verifyResultItems(libraryResult, i2);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$onGetItemOnHandler$1(ListenableFuture listenableFuture, MediaSession.ControllerInfo controllerInfo) {
        LibraryResult<?> libraryResult = (LibraryResult) tryGetFutureResult(listenableFuture);
        if (libraryResult != null) {
            maybeUpdateLegacyErrorState(controllerInfo, libraryResult);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$onGetSearchResultOnHandler$6(ListenableFuture listenableFuture, MediaSession.ControllerInfo controllerInfo, int i2) {
        LibraryResult<?> libraryResult = (LibraryResult) tryGetFutureResult(listenableFuture);
        if (libraryResult != null) {
            maybeUpdateLegacyErrorState(controllerInfo, libraryResult);
            verifyResultItems(libraryResult, i2);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$onSearchOnHandler$5(ListenableFuture listenableFuture, MediaSession.ControllerInfo controllerInfo) {
        LibraryResult<?> libraryResult = (LibraryResult) tryGetFutureResult(listenableFuture);
        if (libraryResult != null) {
            maybeUpdateLegacyErrorState(controllerInfo, libraryResult);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$onSubscribeOnHandler$2(ListenableFuture listenableFuture, MediaSession.ControllerInfo controllerInfo, String str) {
        LibraryResult libraryResult = (LibraryResult) tryGetFutureResult(listenableFuture);
        if (libraryResult == null || libraryResult.resultCode != 0) {
            lambda$onUnsubscribeOnHandler$3(controllerInfo, str);
        }
    }

    private void maybeUpdateLegacyErrorState(MediaSession.ControllerInfo controllerInfo, LibraryResult<?> libraryResult) {
        if (this.libraryErrorReplicationMode == 0 || controllerInfo.getControllerVersion() != 0) {
            return;
        }
        if (isReplicationErrorCode(libraryResult.resultCode)) {
            getMediaSessionLegacyStub().setLegacyError(libraryResult, this.libraryErrorReplicationMode == 1);
        }
        if (libraryResult.resultCode == 0) {
            getMediaSessionLegacyStub().clearLegacyErrorStatus();
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void postOrRunOnApplicationHandler(Runnable runnable) {
        Util.postOrRun(getApplicationHandler(), runnable);
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* JADX INFO: renamed from: removeSubscription, reason: merged with bridge method [inline-methods] */
    public void lambda$onUnsubscribeOnHandler$3(MediaSession.ControllerInfo controllerInfo, String str) {
        MediaSession.ControllerCb controllerCb = (MediaSession.ControllerCb) Assertions.checkNotNull(controllerInfo.getControllerCb());
        this.parentIdToSubscribedControllers.remove(str, controllerInfo);
        this.controllerToSubscribedParentIds.remove(controllerCb, str);
    }

    @Nullable
    private static <T> T tryGetFutureResult(Future<T> future) {
        Assertions.checkState(future.isDone());
        try {
            return future.get();
        } catch (InterruptedException | CancellationException | ExecutionException e2) {
            Log.w(MediaSessionImpl.TAG, "Library operation failed", e2);
            return null;
        }
    }

    private static void verifyResultItems(LibraryResult<ImmutableList<MediaItem>> libraryResult, int i2) {
        if (libraryResult.resultCode == 0) {
            List list = (List) Assertions.checkNotNull(libraryResult.value);
            if (list.size() <= i2) {
                return;
            }
            throw new IllegalStateException("Invalid size=" + list.size() + ", pageSize=" + i2);
        }
    }

    public void clearReplicatedLibraryError() {
        getMediaSessionLegacyStub().clearLegacyErrorStatus();
    }

    @Override // androidx.media3.session.MediaSessionImpl
    protected MediaSessionServiceLegacyStub createLegacyBrowserService(MediaSessionCompat.Token token) {
        MediaLibraryServiceLegacyStub mediaLibraryServiceLegacyStub = new MediaLibraryServiceLegacyStub(this);
        mediaLibraryServiceLegacyStub.initialize(token);
        return mediaLibraryServiceLegacyStub;
    }

    @Override // androidx.media3.session.MediaSessionImpl
    protected void dispatchRemoteControllerTaskWithoutReturn(MediaSessionImpl.RemoteControllerTask remoteControllerTask) {
        super.dispatchRemoteControllerTaskWithoutReturn(remoteControllerTask);
        MediaLibraryServiceLegacyStub legacyBrowserService = getLegacyBrowserService();
        if (legacyBrowserService != null) {
            try {
                remoteControllerTask.run(legacyBrowserService.getBrowserLegacyCbForBroadcast(), 0);
            } catch (RemoteException e2) {
                Log.e(MediaSessionImpl.TAG, "Exception in using media1 API", e2);
            }
        }
    }

    @Override // androidx.media3.session.MediaSessionImpl
    public List<MediaSession.ControllerInfo> getConnectedControllers() {
        List<MediaSession.ControllerInfo> connectedControllers = super.getConnectedControllers();
        MediaLibraryServiceLegacyStub legacyBrowserService = getLegacyBrowserService();
        if (legacyBrowserService == null) {
            return connectedControllers;
        }
        ImmutableList<MediaSession.ControllerInfo> connectedControllers2 = legacyBrowserService.getConnectedControllersManager().getConnectedControllers();
        return ImmutableList.builderWithExpectedSize(connectedControllers.size() + connectedControllers2.size()).addAll(connectedControllers).addAll(connectedControllers2).build();
    }

    public ImmutableList<MediaSession.ControllerInfo> getSubscribedControllers(String str) {
        return ImmutableList.copyOf(this.parentIdToSubscribedControllers.get(str));
    }

    @Override // androidx.media3.session.MediaSessionImpl
    public boolean isConnected(MediaSession.ControllerInfo controllerInfo) {
        if (super.isConnected(controllerInfo)) {
            return true;
        }
        MediaLibraryServiceLegacyStub legacyBrowserService = getLegacyBrowserService();
        return legacyBrowserService != null && legacyBrowserService.getConnectedControllersManager().isConnected(controllerInfo);
    }

    public void notifyChildrenChanged(String str, int i2, @Nullable MediaLibraryService.LibraryParams libraryParams) {
        List<MediaSession.ControllerInfo> connectedControllers = this.instance.getConnectedControllers();
        for (int i3 = 0; i3 < connectedControllers.size(); i3++) {
            notifyChildrenChanged(connectedControllers.get(i3), str, i2, libraryParams);
        }
    }

    public void notifySearchResultChanged(MediaSession.ControllerInfo controllerInfo, final String str, final int i2, @Nullable final MediaLibraryService.LibraryParams libraryParams) {
        if (isMediaNotificationControllerConnected() && isMediaNotificationController(controllerInfo) && (controllerInfo = getSystemUiControllerInfo()) == null) {
            return;
        }
        dispatchRemoteControllerTaskWithoutReturn(controllerInfo, new MediaSessionImpl.RemoteControllerTask() { // from class: androidx.media3.session.l2
            @Override // androidx.media3.session.MediaSessionImpl.RemoteControllerTask
            public final void run(MediaSession.ControllerCb controllerCb, int i3) throws RemoteException {
                controllerCb.onSearchResultChanged(i3, str, i2, libraryParams);
            }
        });
    }

    @Override // androidx.media3.session.MediaSessionImpl
    public void onDisconnectedOnHandler(MediaSession.ControllerInfo controllerInfo) {
        UnmodifiableIterator it = ImmutableSet.copyOf(this.controllerToSubscribedParentIds.get((MediaSession.ControllerCb) Assertions.checkNotNull(controllerInfo.getControllerCb()))).iterator();
        while (it.hasNext()) {
            lambda$onUnsubscribeOnHandler$3(controllerInfo, (String) it.next());
        }
        super.onDisconnectedOnHandler(controllerInfo);
    }

    public ListenableFuture onGetChildrenOnHandler(final MediaSession.ControllerInfo controllerInfo, String str, int i2, final int i3, @Nullable MediaLibraryService.LibraryParams libraryParams) {
        if (Objects.equals(str, RECENT_LIBRARY_ROOT_MEDIA_ID)) {
            return !canResumePlaybackOnStart() ? Futures.immediateFuture(LibraryResult.ofError(-6)) : getPlayerWrapper().getPlaybackState() == 1 ? getRecentMediaItemAtDeviceBootTime(controllerInfo, libraryParams) : Futures.immediateFuture(LibraryResult.ofItemList(ImmutableList.of(new MediaItem.Builder().setMediaId("androidx.media3.session.recent.item").setMediaMetadata(new MediaMetadata.Builder().setIsBrowsable(Boolean.FALSE).setIsPlayable(Boolean.TRUE).build()).build()), libraryParams));
        }
        final ListenableFuture listenableFutureOnGetChildren = this.callback.onGetChildren(this.instance, resolveControllerInfoForCallback(controllerInfo), str, i2, i3, libraryParams);
        listenableFutureOnGetChildren.addListener(new Runnable() { // from class: androidx.media3.session.h2
            @Override // java.lang.Runnable
            public final void run() {
                this.f2683b.lambda$onGetChildrenOnHandler$0(listenableFutureOnGetChildren, controllerInfo, i3);
            }
        }, new ExecutorC0278i2(this));
        return listenableFutureOnGetChildren;
    }

    public ListenableFuture onGetItemOnHandler(final MediaSession.ControllerInfo controllerInfo, String str) {
        final ListenableFuture listenableFutureOnGetItem = this.callback.onGetItem(this.instance, resolveControllerInfoForCallback(controllerInfo), str);
        listenableFutureOnGetItem.addListener(new Runnable() { // from class: androidx.media3.session.k2
            @Override // java.lang.Runnable
            public final void run() {
                this.f2714b.lambda$onGetItemOnHandler$1(listenableFutureOnGetItem, controllerInfo);
            }
        }, new ExecutorC0278i2(this));
        return listenableFutureOnGetItem;
    }

    public ListenableFuture onGetLibraryRootOnHandler(MediaSession.ControllerInfo controllerInfo, @Nullable MediaLibraryService.LibraryParams libraryParams) {
        return (libraryParams != null && libraryParams.isRecent && isSystemUiController(controllerInfo)) ? !canResumePlaybackOnStart() ? Futures.immediateFuture(LibraryResult.ofError(-6)) : Futures.immediateFuture(LibraryResult.ofItem(new MediaItem.Builder().setMediaId(RECENT_LIBRARY_ROOT_MEDIA_ID).setMediaMetadata(new MediaMetadata.Builder().setIsBrowsable(Boolean.TRUE).setIsPlayable(Boolean.FALSE).build()).build(), libraryParams)) : this.callback.onGetLibraryRoot(this.instance, resolveControllerInfoForCallback(controllerInfo), libraryParams);
    }

    public ListenableFuture onGetSearchResultOnHandler(final MediaSession.ControllerInfo controllerInfo, String str, int i2, final int i3, @Nullable MediaLibraryService.LibraryParams libraryParams) {
        final ListenableFuture listenableFutureOnGetSearchResult = this.callback.onGetSearchResult(this.instance, resolveControllerInfoForCallback(controllerInfo), str, i2, i3, libraryParams);
        listenableFutureOnGetSearchResult.addListener(new Runnable() { // from class: androidx.media3.session.m2
            @Override // java.lang.Runnable
            public final void run() {
                this.f2754b.lambda$onGetSearchResultOnHandler$6(listenableFutureOnGetSearchResult, controllerInfo, i3);
            }
        }, new ExecutorC0278i2(this));
        return listenableFutureOnGetSearchResult;
    }

    public ListenableFuture onSearchOnHandler(final MediaSession.ControllerInfo controllerInfo, String str, @Nullable MediaLibraryService.LibraryParams libraryParams) {
        final ListenableFuture listenableFutureOnSearch = this.callback.onSearch(this.instance, resolveControllerInfoForCallback(controllerInfo), str, libraryParams);
        listenableFutureOnSearch.addListener(new Runnable() { // from class: androidx.media3.session.o2
            @Override // java.lang.Runnable
            public final void run() {
                this.f2791b.lambda$onSearchOnHandler$5(listenableFutureOnSearch, controllerInfo);
            }
        }, new ExecutorC0278i2(this));
        return listenableFutureOnSearch;
    }

    public ListenableFuture onSubscribeOnHandler(final MediaSession.ControllerInfo controllerInfo, final String str, @Nullable MediaLibraryService.LibraryParams libraryParams) {
        this.controllerToSubscribedParentIds.put((MediaSession.ControllerCb) Assertions.checkNotNull(controllerInfo.getControllerCb()), str);
        this.parentIdToSubscribedControllers.put(str, controllerInfo);
        final ListenableFuture listenableFuture = (ListenableFuture) Assertions.checkNotNull(this.callback.onSubscribe(this.instance, resolveControllerInfoForCallback(controllerInfo), str, libraryParams), "onSubscribe must return non-null future");
        listenableFuture.addListener(new Runnable() { // from class: androidx.media3.session.j2
            @Override // java.lang.Runnable
            public final void run() {
                this.f2702b.lambda$onSubscribeOnHandler$2(listenableFuture, controllerInfo, str);
            }
        }, new ExecutorC0278i2(this));
        return listenableFuture;
    }

    public ListenableFuture onUnsubscribeOnHandler(final MediaSession.ControllerInfo controllerInfo, final String str) {
        ListenableFuture listenableFutureOnUnsubscribe = this.callback.onUnsubscribe(this.instance, resolveControllerInfoForCallback(controllerInfo), str);
        listenableFutureOnUnsubscribe.addListener(new Runnable() { // from class: androidx.media3.session.p2
            @Override // java.lang.Runnable
            public final void run() {
                this.f2806b.lambda$onUnsubscribeOnHandler$3(controllerInfo, str);
            }
        }, new ExecutorC0278i2(this));
        return listenableFutureOnUnsubscribe;
    }

    /* JADX INFO: Access modifiers changed from: protected */
    @Override // androidx.media3.session.MediaSessionImpl
    @Nullable
    public MediaLibraryServiceLegacyStub getLegacyBrowserService() {
        return (MediaLibraryServiceLegacyStub) super.getLegacyBrowserService();
    }

    public void notifyChildrenChanged(MediaSession.ControllerInfo controllerInfo, final String str, final int i2, @Nullable final MediaLibraryService.LibraryParams libraryParams) {
        if (isMediaNotificationControllerConnected() && isMediaNotificationController(controllerInfo) && (controllerInfo = getSystemUiControllerInfo()) == null) {
            return;
        }
        dispatchRemoteControllerTaskWithoutReturn(controllerInfo, new MediaSessionImpl.RemoteControllerTask() { // from class: androidx.media3.session.n2
            @Override // androidx.media3.session.MediaSessionImpl.RemoteControllerTask
            public final void run(MediaSession.ControllerCb controllerCb, int i3) throws RemoteException {
                this.f2774a.lambda$notifyChildrenChanged$4(str, i2, libraryParams, controllerCb, i3);
            }
        });
    }
}
