summaryrefslogtreecommitdiff
path: root/services/tests/servicestests/src/com/android/server/audio/AudioDeviceBrokerTest.java
blob: 5c53d43fa1df3580023686a52b7763747c1bbb34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/*
 * Copyright 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.server.audio;

import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioSystem;
import android.util.Log;

import androidx.test.InstrumentationRegistry;
import androidx.test.filters.MediumTest;
import androidx.test.runner.AndroidJUnit4;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Spy;

@MediumTest
@RunWith(AndroidJUnit4.class)
public class AudioDeviceBrokerTest {

    private static final String TAG = "AudioDeviceBrokerTest";
    private static final int MAX_MESSAGE_HANDLING_DELAY_MS = 100;

    private Context mContext;
    // the actual class under test
    private AudioDeviceBroker mAudioDeviceBroker;

    @Mock private AudioService mMockAudioService;
    @Spy private AudioDeviceInventory mSpyDevInventory;
    @Spy private AudioSystemAdapter mSpyAudioSystem;
    @Spy private SystemServerAdapter mSpySystemServer;

    private BluetoothDevice mFakeBtDevice;

    @Before
    public void setUp() throws Exception {
        mContext = InstrumentationRegistry.getTargetContext();

        mMockAudioService = mock(AudioService.class);
        mSpyAudioSystem = spy(new NoOpAudioSystemAdapter());
        mSpyDevInventory = spy(new AudioDeviceInventory(mSpyAudioSystem));
        mSpySystemServer = spy(new NoOpSystemServerAdapter());
        mAudioDeviceBroker = new AudioDeviceBroker(mContext, mMockAudioService, mSpyDevInventory,
                mSpySystemServer);
        mSpyDevInventory.setDeviceBroker(mAudioDeviceBroker);

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        mFakeBtDevice = adapter.getRemoteDevice("00:01:02:03:04:05");
        Assert.assertNotNull("invalid null BT device", mFakeBtDevice);
    }

    @After
    public void tearDown() throws Exception { }

//    @Test
//    public void testSetUpAndTearDown() { }

    /**
     * postBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent() for connection:
     * - verify it calls into AudioDeviceInventory with the right params
     * - verify it calls into AudioSystem and stays connected (no 2nd call to disconnect)
     * @throws Exception
     */
    @Test
    public void testPostA2dpDeviceConnectionChange() throws Exception {
        Log.i(TAG, "starting testPostA2dpDeviceConnectionChange");
        Assert.assertNotNull("invalid null BT device", mFakeBtDevice);

        mAudioDeviceBroker.queueBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(
                new AudioDeviceBroker.BtDeviceConnectionInfo(mFakeBtDevice,
                        BluetoothProfile.STATE_CONNECTED, BluetoothProfile.A2DP, true, 1));
        Thread.sleep(2 * MAX_MESSAGE_HANDLING_DELAY_MS);
        verify(mSpyDevInventory, times(1)).setBluetoothA2dpDeviceConnectionState(
                any(BluetoothDevice.class),
                ArgumentMatchers.eq(BluetoothProfile.STATE_CONNECTED) /*state*/,
                ArgumentMatchers.eq(BluetoothProfile.A2DP) /*profile*/,
                ArgumentMatchers.eq(true) /*suppressNoisyIntent*/, anyInt() /*musicDevice*/,
                ArgumentMatchers.eq(1) /*a2dpVolume*/
        );

        // verify the connection was reported to AudioSystem
        checkSingleSystemConnection(mFakeBtDevice);
    }

    /**
     * Verify call to postBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent() for
     *    connection > pause > disconnection > connection
     * keeps the device connected
     * @throws Exception
     */
    @Test
    public void testA2dpDeviceConnectionDisconnectionConnectionChange() throws Exception {
        Log.i(TAG, "starting testA2dpDeviceConnectionDisconnectionConnectionChange");

        doTestConnectionDisconnectionReconnection(0, false,
                // cannot guarantee single connection since commands are posted in separate thread
                // than they are processed
                false);
    }

    /**
     * Verify device disconnection and reconnection within the BECOMING_NOISY window
     * in the absence of media playback
     * @throws Exception
     */
    @Test
    public void testA2dpDeviceReconnectionWithinBecomingNoisyDelay() throws Exception {
        Log.i(TAG, "starting testA2dpDeviceReconnectionWithinBecomingNoisyDelay");

        doTestConnectionDisconnectionReconnection(AudioService.BECOMING_NOISY_DELAY_MS / 2,
                false,
                // do not check single connection since the connection command will come much
                // after the disconnection command
                false);
    }

    /**
     * Same as testA2dpDeviceConnectionDisconnectionConnectionChange() but with mock media playback
     * @throws Exception
     */
    @Test
    public void testA2dpConnectionDisconnectionConnectionChange_MediaPlayback() throws Exception {
        Log.i(TAG, "starting testA2dpConnectionDisconnectionConnectionChange_MediaPlayback");

        doTestConnectionDisconnectionReconnection(0, true,
                // guarantee single connection since because of media playback the disconnection
                // is supposed to be delayed, and thus cancelled because of the connection
                true);
    }

    /**
     * Same as testA2dpDeviceReconnectionWithinBecomingNoisyDelay() but with mock media playback
     * @throws Exception
     */
    @Test
    public void testA2dpReconnectionWithinBecomingNoisyDelay_MediaPlayback() throws Exception {
        Log.i(TAG, "starting testA2dpReconnectionWithinBecomingNoisyDelay_MediaPlayback");

        doTestConnectionDisconnectionReconnection(AudioService.BECOMING_NOISY_DELAY_MS / 2,
                true,
                // guarantee single connection since because of media playback the disconnection
                // is supposed to be delayed, and thus cancelled because of the connection
                true);
    }

    /**
     * Test that device wired state intents are broadcasted on connection state change
     * @throws Exception
     */
    @Test
    public void testSetWiredDeviceConnectionState() throws Exception {
        Log.i(TAG, "starting postSetWiredDeviceConnectionState");

        final String address = "testAddress";
        final String name = "testName";
        final String caller = "testCaller";

        doNothing().when(mSpySystemServer).broadcastStickyIntentToCurrentProfileGroup(
                any(Intent.class));

        mSpyDevInventory.setWiredDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
                AudioService.CONNECTION_STATE_CONNECTED, address, name, caller);
        Thread.sleep(MAX_MESSAGE_HANDLING_DELAY_MS);

        // Verify that the sticky intent is broadcasted
        verify(mSpySystemServer, times(1)).broadcastStickyIntentToCurrentProfileGroup(
                any(Intent.class));
    }

    private void doTestConnectionDisconnectionReconnection(int delayAfterDisconnection,
            boolean mockMediaPlayback, boolean guaranteeSingleConnection) throws Exception {
        when(mMockAudioService.getDeviceForStream(AudioManager.STREAM_MUSIC))
                .thenReturn(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
        when(mMockAudioService.isInCommunication()).thenReturn(false);
        when(mMockAudioService.hasMediaDynamicPolicy()).thenReturn(false);
        when(mMockAudioService.hasAudioFocusUsers()).thenReturn(false);

        ((NoOpAudioSystemAdapter) mSpyAudioSystem).configureIsStreamActive(mockMediaPlayback);

        // first connection: ensure the device is connected as a starting condition for the test
        mAudioDeviceBroker.queueBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(
                new AudioDeviceBroker.BtDeviceConnectionInfo(mFakeBtDevice,
                        BluetoothProfile.STATE_CONNECTED, BluetoothProfile.A2DP, true, 1));
        Thread.sleep(MAX_MESSAGE_HANDLING_DELAY_MS);

        // disconnection
        mAudioDeviceBroker.queueBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(
                new AudioDeviceBroker.BtDeviceConnectionInfo(mFakeBtDevice,
                        BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.A2DP, false, -1));
        if (delayAfterDisconnection > 0) {
            Thread.sleep(delayAfterDisconnection);
        }

        // reconnection
        mAudioDeviceBroker.queueBluetoothA2dpDeviceConnectionStateSuppressNoisyIntent(
                new AudioDeviceBroker.BtDeviceConnectionInfo(mFakeBtDevice,
                        BluetoothProfile.STATE_CONNECTED, BluetoothProfile.A2DP, true, 2));
        Thread.sleep(AudioService.BECOMING_NOISY_DELAY_MS + MAX_MESSAGE_HANDLING_DELAY_MS);

        // Verify disconnection has been cancelled and we're seeing two connections attempts,
        // with the device connected at the end of the test
        verify(mSpyDevInventory, times(2)).onSetA2dpSinkConnectionState(
                any(BtHelper.BluetoothA2dpDeviceInfo.class),
                ArgumentMatchers.eq(BluetoothProfile.STATE_CONNECTED));
        Assert.assertTrue("Mock device not connected",
                mSpyDevInventory.isA2dpDeviceConnected(mFakeBtDevice));

        if (guaranteeSingleConnection) {
            // when the disconnection was expected to be cancelled, there should have been a single
            //  call to AudioSystem to declare the device connected (available)
            checkSingleSystemConnection(mFakeBtDevice);
        }
    }

    /**
     * Verifies the given device was reported to AudioSystem exactly once as available
     * @param btDevice
     * @throws Exception
     */
    private void checkSingleSystemConnection(BluetoothDevice btDevice) throws Exception {
        final String expectedName = btDevice.getName() == null ? "" : btDevice.getName();
        verify(mSpyAudioSystem, times(1)).setDeviceConnectionState(
                ArgumentMatchers.eq(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
                ArgumentMatchers.eq(AudioSystem.DEVICE_STATE_AVAILABLE),
                ArgumentMatchers.eq(btDevice.getAddress()),
                ArgumentMatchers.eq(expectedName),
                anyInt() /*codec*/);
    }
}