• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.systemui.media
18 
19 import android.content.ComponentName
20 import android.content.Context
21 import android.media.session.MediaController
22 import android.media.session.MediaController.PlaybackInfo
23 import android.media.session.MediaSession
24 import android.media.session.MediaSessionManager
25 import android.util.Log
26 import com.android.systemui.dagger.qualifiers.Background
27 import com.android.systemui.dagger.qualifiers.Main
28 import com.android.systemui.statusbar.phone.NotificationListenerWithPlugins
29 import java.util.concurrent.Executor
30 import javax.inject.Inject
31 
32 private const val TAG = "MediaSessionBasedFilter"
33 
34 /**
35  * Filters media loaded events for local media sessions while an app is casting.
36  *
37  * When an app is casting there can be one remote media sessions and potentially more local media
38  * sessions. In this situation, there should only be a media object for the remote session. To
39  * achieve this, update events for the local session need to be filtered.
40  */
41 class MediaSessionBasedFilter @Inject constructor(
42     context: Context,
43     private val sessionManager: MediaSessionManager,
44     @Main private val foregroundExecutor: Executor,
45     @Background private val backgroundExecutor: Executor
46 ) : MediaDataManager.Listener {
47 
48     private val listeners: MutableSet<MediaDataManager.Listener> = mutableSetOf()
49 
50     // Keep track of MediaControllers for a given package to check if an app is casting and it
51     // filter loaded events for local sessions.
52     private val packageControllers: LinkedHashMap<String, MutableList<MediaController>> =
53             LinkedHashMap()
54 
55     // Keep track of the key used for the session tokens. This information is used to know when to
56     // dispatch a removed event so that a media object for a local session will be removed.
57     private val keyedTokens: MutableMap<String, MutableSet<MediaSession.Token>> = mutableMapOf()
58 
59     // Keep track of which media session tokens have associated notifications.
60     private val tokensWithNotifications: MutableSet<MediaSession.Token> = mutableSetOf()
61 
62     private val sessionListener = object : MediaSessionManager.OnActiveSessionsChangedListener {
63         override fun onActiveSessionsChanged(controllers: List<MediaController>) {
64             handleControllersChanged(controllers)
65         }
66     }
67 
68     init {
69         backgroundExecutor.execute {
70             val name = ComponentName(context, NotificationListenerWithPlugins::class.java)
71             sessionManager.addOnActiveSessionsChangedListener(sessionListener, name)
72             handleControllersChanged(sessionManager.getActiveSessions(name))
73         }
74     }
75 
76     /**
77      * Add a listener for filtered [MediaData] changes
78      */
79     fun addListener(listener: MediaDataManager.Listener) = listeners.add(listener)
80 
81     /**
82      * Remove a listener that was registered with addListener
83      */
84     fun removeListener(listener: MediaDataManager.Listener) = listeners.remove(listener)
85 
86     /**
87      * May filter loaded events by not passing them along to listeners.
88      *
89      * If an app has only one session with playback type PLAYBACK_TYPE_REMOTE, then assuming that
90      * the app is casting. Sometimes apps will send redundant updates to a local session with
91      * playback type PLAYBACK_TYPE_LOCAL. These updates should be filtered to improve the usability
92      * of the media controls.
93      */
94     override fun onMediaDataLoaded(key: String, oldKey: String?, info: MediaData) {
95         backgroundExecutor.execute {
96             info.token?.let {
97                 tokensWithNotifications.add(it)
98             }
99             val isMigration = oldKey != null && key != oldKey
100             if (isMigration) {
101                 keyedTokens.remove(oldKey)?.let { removed -> keyedTokens.put(key, removed) }
102             }
103             if (info.token != null) {
104                 keyedTokens.get(key)?.let {
105                     tokens ->
106                     tokens.add(info.token)
107                 } ?: run {
108                     val tokens = mutableSetOf(info.token)
109                     keyedTokens.put(key, tokens)
110                 }
111             }
112             // Determine if an app is casting by checking if it has a session with playback type
113             // PLAYBACK_TYPE_REMOTE.
114             val remoteControllers = packageControllers.get(info.packageName)?.filter {
115                 it.playbackInfo?.playbackType == PlaybackInfo.PLAYBACK_TYPE_REMOTE
116             }
117             // Limiting search to only apps with a single remote session.
118             val remote = if (remoteControllers?.size == 1) remoteControllers.firstOrNull() else null
119             if (isMigration || remote == null || remote.sessionToken == info.token ||
120                     !tokensWithNotifications.contains(remote.sessionToken)) {
121                 // Not filtering in this case. Passing the event along to listeners.
122                 dispatchMediaDataLoaded(key, oldKey, info)
123             } else {
124                 // Filtering this event because the app is casting and the loaded events is for a
125                 // local session.
126                 Log.d(TAG, "filtering key=$key local=${info.token} remote=${remote?.sessionToken}")
127                 // If the local session uses a different notification key, then lets go a step
128                 // farther and dismiss the media data so that media controls for the local session
129                 // don't hang around while casting.
130                 if (!keyedTokens.get(key)!!.contains(remote.sessionToken)) {
131                     dispatchMediaDataRemoved(key)
132                 }
133             }
134         }
135     }
136 
137     override fun onMediaDataRemoved(key: String) {
138         // Queue on background thread to ensure ordering of loaded and removed events is maintained.
139         backgroundExecutor.execute {
140             keyedTokens.remove(key)
141             dispatchMediaDataRemoved(key)
142         }
143     }
144 
145     private fun dispatchMediaDataLoaded(key: String, oldKey: String?, info: MediaData) {
146         foregroundExecutor.execute {
147             listeners.toSet().forEach { it.onMediaDataLoaded(key, oldKey, info) }
148         }
149     }
150 
151     private fun dispatchMediaDataRemoved(key: String) {
152         foregroundExecutor.execute {
153             listeners.toSet().forEach { it.onMediaDataRemoved(key) }
154         }
155     }
156 
157     private fun handleControllersChanged(controllers: List<MediaController>) {
158         packageControllers.clear()
159         controllers.forEach {
160             controller ->
161             packageControllers.get(controller.packageName)?.let {
162                 tokens ->
163                 tokens.add(controller)
164             } ?: run {
165                 val tokens = mutableListOf(controller)
166                 packageControllers.put(controller.packageName, tokens)
167             }
168         }
169         tokensWithNotifications.retainAll(controllers.map { it.sessionToken })
170     }
171 }
172