blob: 4b7f698ce32fed1ff7a8652b783a541df0318a0e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
John Spurlock61560172015-02-06 19:46:04 -050017package com.android.server.audio;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Jeff Sharkey098d5802012-04-26 17:30:34 -070019import static android.Manifest.permission.REMOTE_AUDIO_PLAYBACK;
Amith Yamasanic696a532011-10-28 17:02:37 -070020import static android.media.AudioManager.RINGER_MODE_NORMAL;
21import static android.media.AudioManager.RINGER_MODE_SILENT;
22import static android.media.AudioManager.RINGER_MODE_VIBRATE;
23
Glenn Kastenfd116ad2013-07-12 17:10:39 -070024import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.app.ActivityManagerNative;
Dianne Hackbornba50b97c2013-04-30 15:04:46 -070026import android.app.AppOpsManager;
Amith Yamasani6243edd2011-12-05 19:58:48 -080027import android.app.KeyguardManager;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -070028import android.bluetooth.BluetoothA2dp;
29import android.bluetooth.BluetoothAdapter;
30import android.bluetooth.BluetoothClass;
31import android.bluetooth.BluetoothDevice;
32import android.bluetooth.BluetoothHeadset;
33import android.bluetooth.BluetoothProfile;
Nick Pellybd022f42009-08-14 18:33:38 -070034import android.content.BroadcastReceiver;
Jean-Michel Trivid327f212010-03-16 21:44:33 -070035import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
Eric Laurenta553c252009-07-17 12:17:14 -070039import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.PackageManager;
Jean-Michel Trivif26f0172012-04-25 16:23:20 -070041import android.content.res.Configuration;
Eric Laurente78fced2013-03-15 16:03:47 -070042import android.content.res.Resources;
43import android.content.res.XmlResourceParser;
Jason Parekhb1096152009-03-24 17:48:25 -070044import android.database.ContentObserver;
Jungshik Jang41d97462014-06-30 22:26:29 +090045import android.hardware.hdmi.HdmiControlManager;
Eric Laurent212532b2014-07-21 15:43:18 -070046import android.hardware.hdmi.HdmiPlaybackClient;
Jungshik Jang41d97462014-06-30 22:26:29 +090047import android.hardware.hdmi.HdmiTvClient;
Paul McLeanc837a452014-04-09 09:04:43 -070048import android.hardware.usb.UsbManager;
John Spurlock61560172015-02-06 19:46:04 -050049import android.media.AudioAttributes;
50import android.media.AudioDevicePort;
51import android.media.AudioSystem;
52import android.media.AudioFormat;
53import android.media.AudioManager;
54import android.media.AudioManagerInternal;
55import android.media.AudioPort;
56import android.media.AudioRoutesInfo;
John Spurlock61560172015-02-06 19:46:04 -050057import android.media.IAudioFocusDispatcher;
58import android.media.IAudioRoutesObserver;
59import android.media.IAudioService;
60import android.media.IRemoteControlDisplay;
61import android.media.IRingtonePlayer;
62import android.media.IVolumeController;
63import android.media.MediaPlayer;
64import android.media.SoundPool;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.media.MediaPlayer.OnCompletionListener;
66import android.media.MediaPlayer.OnErrorListener;
Jean-Michel Trivi958876f2014-11-16 15:40:22 -080067import android.media.audiopolicy.AudioPolicy;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -070068import android.media.audiopolicy.AudioPolicyConfig;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -080069import android.media.audiopolicy.IAudioPolicyCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Binder;
Eric Laurentc18c9132013-04-12 17:24:56 -070071import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Environment;
73import android.os.Handler;
74import android.os.IBinder;
75import android.os.Looper;
76import android.os.Message;
Jean-Michel Trivic6802222012-04-30 11:15:03 -070077import android.os.PowerManager;
Dianne Hackborn632ca412012-06-14 19:34:10 -070078import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.RemoteException;
John Spurlock33f4e042014-07-11 13:10:58 -040080import android.os.SystemClock;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -070081import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070082import android.os.UserHandle;
Eric Laurentbffc3d12012-05-07 17:43:49 -070083import android.os.Vibrator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.provider.Settings;
85import android.provider.Settings.System;
Tyler Gunnef9f6f92014-09-12 22:16:17 -070086import android.telecom.TelecomManager;
Dianne Hackborn632ca412012-06-14 19:34:10 -070087import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.util.Log;
John Spurlockaa5ee4d2014-07-25 13:05:12 -040089import android.util.MathUtils;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -070090import android.util.Slog;
John Spurlock2bb02ec2015-03-02 13:13:06 -050091import android.util.SparseIntArray;
Jean-Michel Trivid327f212010-03-16 21:44:33 -070092import android.view.KeyEvent;
RoboErik519c7742014-11-18 10:59:09 -080093import android.view.OrientationEventListener;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -070094import android.view.Surface;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -070095import android.view.WindowManager;
Jean-Michel Trivi873cc452014-09-11 17:25:09 -070096import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Eric Laurente78fced2013-03-15 16:03:47 -070098import com.android.internal.util.XmlUtils;
RoboErik0dac35a2014-08-12 15:48:49 -070099import com.android.server.LocalServices;
Eric Laurente78fced2013-03-15 16:03:47 -0700100
101import org.xmlpull.v1.XmlPullParserException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -0800103import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.io.IOException;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -0800105import java.io.PrintWriter;
Eric Laurente78fced2013-03-15 16:03:47 -0700106import java.lang.reflect.Field;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700108import java.util.HashMap;
109import java.util.Iterator;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700110import java.util.List;
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700111import java.util.Map;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700112import java.util.NoSuchElementException;
RoboErikd09bd0c2014-06-24 17:45:19 -0700113import java.util.Objects;
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700114import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
116/**
117 * The implementation of the volume manager service.
118 * <p>
119 * This implementation focuses on delivering a responsive UI. Most methods are
120 * asynchronous to external calls. For example, the task of setting a volume
121 * will update our internal state, but in a separate thread will set the system
122 * volume and later persist to the database. Similarly, setting the ringer mode
123 * will update the state and broadcast a change and in a separate thread later
124 * persist the ringer mode.
125 *
126 * @hide
127 */
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700128public class AudioService extends IAudioService.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
130 private static final String TAG = "AudioService";
131
Jean-Michel Trivi339567d2014-07-29 09:53:34 -0700132 /** Debug audio mode */
133 protected static final boolean DEBUG_MODE = Log.isLoggable(TAG + ".MOD", Log.DEBUG);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -0700134
135 /** Debug audio policy feature */
136 protected static final boolean DEBUG_AP = Log.isLoggable(TAG + ".AP", Log.DEBUG);
137
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700138 /** Debug volumes */
John Spurlockae641c92014-06-30 18:11:40 -0400139 protected static final boolean DEBUG_VOL = Log.isLoggable(TAG + ".VOL", Log.DEBUG);
Jean-Michel Trivi18e7bce2011-08-26 12:11:36 -0700140
RoboErik430fc482014-06-12 15:49:20 -0700141 /** debug calls to media session apis */
John Spurlockae641c92014-06-30 18:11:40 -0400142 private static final boolean DEBUG_SESSIONS = Log.isLoggable(TAG + ".SESSIONS", Log.DEBUG);
RoboErik8a2cfc32014-05-16 11:19:38 -0700143
John Spurlock86005342014-05-23 11:58:00 -0400144 /** Allow volume changes to set ringer mode to silent? */
145 private static final boolean VOLUME_SETS_RINGER_MODE_SILENT = false;
146
John Spurlocka11b4af2014-06-01 11:52:23 -0400147 /** In silent mode, are volume adjustments (raises) prevented? */
148 private static final boolean PREVENT_VOLUME_ADJUSTMENT_IF_SILENT = true;
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 /** How long to delay before persisting a change in volume/ringer mode. */
RoboErik45edba12012-03-27 17:54:36 -0700151 private static final int PERSIST_DELAY = 500;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
RoboErik5452e252015-02-06 15:33:53 -0800153 /** How long to delay after a volume down event before unmuting a stream */
154 private static final int UNMUTE_STREAM_DELAY = 350;
155
John Spurlock3346a802014-05-20 16:25:37 -0400156 /**
John Spurlocka11b4af2014-06-01 11:52:23 -0400157 * Only used in the result from {@link #checkForRingerModeChange(int, int, int)}
158 */
159 private static final int FLAG_ADJUST_VOLUME = 1;
160
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700161 private final Context mContext;
162 private final ContentResolver mContentResolver;
163 private final AppOpsManager mAppOps;
Eric Laurent212532b2014-07-21 15:43:18 -0700164
Eric Laurent212532b2014-07-21 15:43:18 -0700165 // the platform type affects volume and silent mode behavior
166 private final int mPlatformType;
167
168 private boolean isPlatformVoice() {
John Spurlock61560172015-02-06 19:46:04 -0500169 return mPlatformType == AudioSystem.PLATFORM_VOICE;
Eric Laurent212532b2014-07-21 15:43:18 -0700170 }
171
172 private boolean isPlatformTelevision() {
John Spurlock61560172015-02-06 19:46:04 -0500173 return mPlatformType == AudioSystem.PLATFORM_TELEVISION;
Eric Laurent212532b2014-07-21 15:43:18 -0700174 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -0800175
John Spurlock3346a802014-05-20 16:25:37 -0400176 /** The controller for the volume UI. */
177 private final VolumeController mVolumeController = new VolumeController();
John Spurlockcdb57ae2015-02-11 19:04:11 -0500178 private final ControllerService mControllerService = new ControllerService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
180 // sendMsg() flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 /** If the msg is already queued, replace it with this one. */
182 private static final int SENDMSG_REPLACE = 0;
183 /** If the msg is already queued, ignore this one and leave the old. */
184 private static final int SENDMSG_NOOP = 1;
185 /** If the msg is already queued, queue this one and leave the old. */
186 private static final int SENDMSG_QUEUE = 2;
187
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700188 // AudioHandler messages
Eric Laurent9bc8358d2011-11-18 16:43:31 -0800189 private static final int MSG_SET_DEVICE_VOLUME = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private static final int MSG_PERSIST_VOLUME = 1;
191 private static final int MSG_PERSIST_RINGER_MODE = 3;
Eric Laurentbffc3d12012-05-07 17:43:49 -0700192 private static final int MSG_MEDIA_SERVER_DIED = 4;
Eric Laurentdfb881f2013-07-18 14:41:39 -0700193 private static final int MSG_PLAY_SOUND_EFFECT = 5;
194 private static final int MSG_BTA2DP_DOCK_TIMEOUT = 6;
195 private static final int MSG_LOAD_SOUND_EFFECTS = 7;
196 private static final int MSG_SET_FORCE_USE = 8;
197 private static final int MSG_BT_HEADSET_CNCT_FAILED = 9;
198 private static final int MSG_SET_ALL_VOLUMES = 10;
199 private static final int MSG_PERSIST_MASTER_VOLUME_MUTE = 11;
200 private static final int MSG_REPORT_NEW_ROUTES = 12;
201 private static final int MSG_SET_FORCE_BT_A2DP_USE = 13;
202 private static final int MSG_CHECK_MUSIC_ACTIVE = 14;
203 private static final int MSG_BROADCAST_AUDIO_BECOMING_NOISY = 15;
204 private static final int MSG_CONFIGURE_SAFE_MEDIA_VOLUME = 16;
205 private static final int MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED = 17;
206 private static final int MSG_PERSIST_SAFE_VOLUME_STATE = 18;
207 private static final int MSG_BROADCAST_BT_CONNECTION_STATE = 19;
208 private static final int MSG_UNLOAD_SOUND_EFFECTS = 20;
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700209 private static final int MSG_SYSTEM_READY = 21;
John Spurlockaa5ee4d2014-07-25 13:05:12 -0400210 private static final int MSG_PERSIST_MUSIC_ACTIVE_MS = 22;
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400211 private static final int MSG_PERSIST_MICROPHONE_MUTE = 23;
RoboErik5452e252015-02-06 15:33:53 -0800212 private static final int MSG_UNMUTE_STREAM = 24;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700213 // start of messages handled under wakelock
214 // these messages can only be queued, i.e. sent with queueMsgUnderWakeLock(),
Jean-Michel Trivie12c39b2012-06-06 10:51:58 -0700215 // and not with sendMsg(..., ..., SENDMSG_QUEUE, ...)
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700216 private static final int MSG_SET_WIRED_DEVICE_CONNECTION_STATE = 100;
Mike Lockwood0a40ec22014-05-21 10:08:50 -0700217 private static final int MSG_SET_A2DP_SRC_CONNECTION_STATE = 101;
218 private static final int MSG_SET_A2DP_SINK_CONNECTION_STATE = 102;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700219 // end of messages handled under wakelock
Eric Laurentafbb0472011-12-15 09:04:23 -0800220
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -0700221 private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000;
Eric Laurentdc03c612011-04-01 10:59:41 -0700222 // Timeout for connection to bluetooth headset service
223 private static final int BT_HEADSET_CNCT_TIMEOUT_MS = 3000;
224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 /** @see AudioSystemThread */
226 private AudioSystemThread mAudioSystemThread;
227 /** @see AudioHandler */
228 private AudioHandler mAudioHandler;
229 /** @see VolumeStreamState */
230 private VolumeStreamState[] mStreamStates;
Jason Parekhb1096152009-03-24 17:48:25 -0700231 private SettingsObserver mSettingsObserver;
Eric Laurenta553c252009-07-17 12:17:14 -0700232
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700233 private int mMode = AudioSystem.MODE_NORMAL;
Glenn Kastenba195eb2011-12-13 09:30:40 -0800234 // protects mRingerMode
235 private final Object mSettingsLock = new Object();
Eric Laurent45c90ce2012-04-24 18:44:22 -0700236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 private SoundPool mSoundPool;
Glenn Kasten30c918c2011-11-10 17:56:41 -0800238 private final Object mSoundEffectsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 private static final int NUM_SOUNDPOOL_CHANNELS = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
Lei Zhang6c798972012-03-02 11:40:12 -0800241 // Maximum volume adjust steps allowed in a single batch call.
242 private static final int MAX_BATCH_VOLUME_ADJUST_STEPS = 4;
243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 /* Sound effect file names */
245 private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
Eric Laurente78fced2013-03-15 16:03:47 -0700246 private static final List<String> SOUND_EFFECT_FILES = new ArrayList<String>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
249 * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
250 * uses soundpool (second column) */
Eric Laurente78fced2013-03-15 16:03:47 -0700251 private final int[][] SOUND_EFFECT_FILES_MAP = new int[AudioManager.NUM_SOUND_EFFECTS][2];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
Jared Suttles59820132009-08-13 21:50:52 -0500253 /** @hide Maximum volume index values for audio streams */
Eric Laurent91377de2014-10-10 15:24:04 -0700254 private static int[] MAX_STREAM_VOLUME = new int[] {
Eric Laurent6ee99522009-08-25 06:30:59 -0700255 5, // STREAM_VOICE_CALL
256 7, // STREAM_SYSTEM
257 7, // STREAM_RING
258 15, // STREAM_MUSIC
259 7, // STREAM_ALARM
260 7, // STREAM_NOTIFICATION
261 15, // STREAM_BLUETOOTH_SCO
262 7, // STREAM_SYSTEM_ENFORCED
263 15, // STREAM_DTMF
264 15 // STREAM_TTS
Jared Suttles59820132009-08-13 21:50:52 -0500265 };
Eric Laurent91377de2014-10-10 15:24:04 -0700266
Eric Laurent6d517662012-04-23 18:42:39 -0700267 /* mStreamVolumeAlias[] indicates for each stream if it uses the volume settings
Eric Laurenta553c252009-07-17 12:17:14 -0700268 * of another stream: This avoids multiplying the volume settings for hidden
269 * stream types that follow other stream behavior for volume settings
Eric Laurent6d517662012-04-23 18:42:39 -0700270 * NOTE: do not create loops in aliases!
271 * Some streams alias to different streams according to device category (phone or tablet) or
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700272 * use case (in call vs off call...). See updateStreamVolumeAlias() for more details.
Eric Laurent212532b2014-07-21 15:43:18 -0700273 * mStreamVolumeAlias contains STREAM_VOLUME_ALIAS_VOICE aliases for a voice capable device
274 * (phone), STREAM_VOLUME_ALIAS_TELEVISION for a television or set-top box and
275 * STREAM_VOLUME_ALIAS_DEFAULT for other devices (e.g. tablets).*/
276 private final int[] STREAM_VOLUME_ALIAS_VOICE = new int[] {
Eric Laurent6d517662012-04-23 18:42:39 -0700277 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL
278 AudioSystem.STREAM_RING, // STREAM_SYSTEM
279 AudioSystem.STREAM_RING, // STREAM_RING
280 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
281 AudioSystem.STREAM_ALARM, // STREAM_ALARM
282 AudioSystem.STREAM_RING, // STREAM_NOTIFICATION
283 AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
284 AudioSystem.STREAM_RING, // STREAM_SYSTEM_ENFORCED
285 AudioSystem.STREAM_RING, // STREAM_DTMF
286 AudioSystem.STREAM_MUSIC // STREAM_TTS
Eric Laurenta553c252009-07-17 12:17:14 -0700287 };
Eric Laurent212532b2014-07-21 15:43:18 -0700288 private final int[] STREAM_VOLUME_ALIAS_TELEVISION = new int[] {
289 AudioSystem.STREAM_MUSIC, // STREAM_VOICE_CALL
290 AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM
291 AudioSystem.STREAM_MUSIC, // STREAM_RING
292 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
293 AudioSystem.STREAM_MUSIC, // STREAM_ALARM
294 AudioSystem.STREAM_MUSIC, // STREAM_NOTIFICATION
295 AudioSystem.STREAM_MUSIC, // STREAM_BLUETOOTH_SCO
296 AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM_ENFORCED
297 AudioSystem.STREAM_MUSIC, // STREAM_DTMF
298 AudioSystem.STREAM_MUSIC // STREAM_TTS
299 };
300 private final int[] STREAM_VOLUME_ALIAS_DEFAULT = new int[] {
Eric Laurent6d517662012-04-23 18:42:39 -0700301 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL
John Spurlock4f0f1202014-08-05 13:28:33 -0400302 AudioSystem.STREAM_RING, // STREAM_SYSTEM
Eric Laurent6d517662012-04-23 18:42:39 -0700303 AudioSystem.STREAM_RING, // STREAM_RING
304 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
305 AudioSystem.STREAM_ALARM, // STREAM_ALARM
306 AudioSystem.STREAM_RING, // STREAM_NOTIFICATION
307 AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
John Spurlock4f0f1202014-08-05 13:28:33 -0400308 AudioSystem.STREAM_RING, // STREAM_SYSTEM_ENFORCED
309 AudioSystem.STREAM_RING, // STREAM_DTMF
Eric Laurent6d517662012-04-23 18:42:39 -0700310 AudioSystem.STREAM_MUSIC // STREAM_TTS
311 };
312 private int[] mStreamVolumeAlias;
Eric Laurenta553c252009-07-17 12:17:14 -0700313
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700314 /**
315 * Map AudioSystem.STREAM_* constants to app ops. This should be used
316 * after mapping through mStreamVolumeAlias.
317 */
John Spurlock59dc9c12015-03-02 11:20:15 -0500318 private static final int[] STREAM_VOLUME_OPS = new int[] {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700319 AppOpsManager.OP_AUDIO_VOICE_VOLUME, // STREAM_VOICE_CALL
320 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_SYSTEM
321 AppOpsManager.OP_AUDIO_RING_VOLUME, // STREAM_RING
322 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_MUSIC
323 AppOpsManager.OP_AUDIO_ALARM_VOLUME, // STREAM_ALARM
324 AppOpsManager.OP_AUDIO_NOTIFICATION_VOLUME, // STREAM_NOTIFICATION
325 AppOpsManager.OP_AUDIO_BLUETOOTH_VOLUME, // STREAM_BLUETOOTH_SCO
326 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_SYSTEM_ENFORCED
327 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_DTMF
328 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_TTS
329 };
330
Eric Laurent83a017b2013-03-19 18:15:31 -0700331 private final boolean mUseFixedVolume;
332
Glenn Kasten30c918c2011-11-10 17:56:41 -0800333 private final AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 public void onError(int error) {
335 switch (error) {
336 case AudioSystem.AUDIO_STATUS_SERVER_DIED:
Eric Laurentdfb881f2013-07-18 14:41:39 -0700337 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED,
338 SENDMSG_NOOP, 0, 0, null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 break;
340 default:
341 break;
342 }
Eric Laurentdfb881f2013-07-18 14:41:39 -0700343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 };
345
346 /**
347 * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
348 * {@link AudioManager#RINGER_MODE_SILENT}, or
349 * {@link AudioManager#RINGER_MODE_VIBRATE}.
350 */
Glenn Kastenba195eb2011-12-13 09:30:40 -0800351 // protected by mSettingsLock
John Spurlock661f2cf2014-11-17 10:29:10 -0500352 private int mRingerMode; // internal ringer mode, affects muting of underlying streams
353 private int mRingerModeExternal = -1; // reported ringer mode to outside clients (AudioManager)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354
Eric Laurent9bcf4012009-06-12 06:09:28 -0700355 /** @see System#MODE_RINGER_STREAMS_AFFECTED */
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700356 private int mRingerModeAffectedStreams = 0;
Eric Laurent9bcf4012009-06-12 06:09:28 -0700357
Eric Laurent5b4e6542010-03-19 20:02:21 -0700358 // Streams currently muted by ringer mode
359 private int mRingerModeMutedStreams;
360
John Spurlock3ce37252015-02-17 13:20:45 -0500361 /** Streams that can be muted. Do not resolve to aliases when checking.
362 * @see System#MUTE_STREAMS_AFFECTED */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 private int mMuteAffectedStreams;
364
365 /**
Eric Laurentbffc3d12012-05-07 17:43:49 -0700366 * NOTE: setVibrateSetting(), getVibrateSetting(), shouldVibrate() are deprecated.
367 * mVibrateSetting is just maintained during deprecation period but vibration policy is
368 * now only controlled by mHasVibrator and mRingerMode
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 */
370 private int mVibrateSetting;
371
Eric Laurentbffc3d12012-05-07 17:43:49 -0700372 // Is there a vibrator
373 private final boolean mHasVibrator;
374
Eric Laurenta553c252009-07-17 12:17:14 -0700375 // Broadcast receiver for device connections intent broadcasts
376 private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
377
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700378 // Devices currently connected
Glenn Kasten30c918c2011-11-10 17:56:41 -0800379 private final HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700380
381 // Forced device usage for communications
382 private int mForcedUseForComm;
383
Eric Laurent9272b4b2010-01-23 17:12:59 -0800384 // List of binder death handlers for setMode() client processes.
385 // The last process to have called setMode() is at the top of the list.
Glenn Kasten30c918c2011-11-10 17:56:41 -0800386 private final ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
Eric Laurenteb14a782009-12-17 03:12:59 -0800387
Eric Laurent3def1ee2010-03-17 23:26:26 -0700388 // List of clients having issued a SCO start request
Glenn Kasten30c918c2011-11-10 17:56:41 -0800389 private final ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
Eric Laurent3def1ee2010-03-17 23:26:26 -0700390
391 // BluetoothHeadset API to control SCO connection
392 private BluetoothHeadset mBluetoothHeadset;
393
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700394 // Bluetooth headset device
395 private BluetoothDevice mBluetoothHeadsetDevice;
Eric Laurent3def1ee2010-03-17 23:26:26 -0700396
Eric Laurent62ef7672010-11-24 10:58:32 -0800397 // Indicate if SCO audio connection is currently active and if the initiator is
398 // audio service (internal) or bluetooth headset (external)
399 private int mScoAudioState;
400 // SCO audio state is not active
401 private static final int SCO_STATE_INACTIVE = 0;
Eric Laurentdc03c612011-04-01 10:59:41 -0700402 // SCO audio activation request waiting for headset service to connect
403 private static final int SCO_STATE_ACTIVATE_REQ = 1;
Eric Laurent25fc29b2013-04-05 12:13:54 -0700404 // SCO audio state is active or starting due to a request from AudioManager API
Eric Laurentdc03c612011-04-01 10:59:41 -0700405 private static final int SCO_STATE_ACTIVE_INTERNAL = 3;
406 // SCO audio deactivation request waiting for headset service to connect
407 private static final int SCO_STATE_DEACTIVATE_REQ = 5;
408
Eric Laurent62ef7672010-11-24 10:58:32 -0800409 // SCO audio state is active due to an action in BT handsfree (either voice recognition or
410 // in call audio)
411 private static final int SCO_STATE_ACTIVE_EXTERNAL = 2;
Eric Laurentdc03c612011-04-01 10:59:41 -0700412 // Deactivation request for all SCO connections (initiated by audio mode change)
413 // waiting for headset service to connect
414 private static final int SCO_STATE_DEACTIVATE_EXT_REQ = 4;
415
Eric Laurentc18c9132013-04-12 17:24:56 -0700416 // Indicates the mode used for SCO audio connection. The mode is virtual call if the request
417 // originated from an app targeting an API version before JB MR2 and raw audio after that.
418 private int mScoAudioMode;
Liejun Taof4e51d82014-07-16 11:18:29 -0700419 // SCO audio mode is undefined
420 private static final int SCO_MODE_UNDEFINED = -1;
Eric Laurentc18c9132013-04-12 17:24:56 -0700421 // SCO audio mode is virtual voice call (BluetoothHeadset.startScoUsingVirtualVoiceCall())
422 private static final int SCO_MODE_VIRTUAL_CALL = 0;
423 // SCO audio mode is raw audio (BluetoothHeadset.connectAudio())
424 private static final int SCO_MODE_RAW = 1;
Liejun Taof4e51d82014-07-16 11:18:29 -0700425 // SCO audio mode is Voice Recognition (BluetoothHeadset.startVoiceRecognition())
426 private static final int SCO_MODE_VR = 2;
427
428 private static final int SCO_MODE_MAX = 2;
Eric Laurentc18c9132013-04-12 17:24:56 -0700429
Eric Laurentdc03c612011-04-01 10:59:41 -0700430 // Current connection state indicated by bluetooth headset
431 private int mScoConnectionState;
Eric Laurent62ef7672010-11-24 10:58:32 -0800432
Eric Laurenta60e2122010-12-28 16:49:07 -0800433 // true if boot sequence has been completed
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700434 private boolean mSystemReady;
Eric Laurenta60e2122010-12-28 16:49:07 -0800435 // listener for SoundPool sample load completion indication
436 private SoundPoolCallback mSoundPoolCallBack;
437 // thread for SoundPool listener
438 private SoundPoolListenerThread mSoundPoolListenerThread;
439 // message looper for SoundPool listener
440 private Looper mSoundPoolLooper = null;
Jean-Michel Trivic55b3932012-06-05 11:57:59 -0700441 // volume applied to sound played with playSoundEffect()
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -0700442 private static int sSoundEffectVolumeDb;
Eric Laurent25101b02011-02-02 09:33:30 -0800443 // previous volume adjustment direction received by checkForRingerModeChange()
444 private int mPrevVolDirection = AudioManager.ADJUST_SAME;
Amith Yamasani6243edd2011-12-05 19:58:48 -0800445 // Keyguard manager proxy
446 private KeyguardManager mKeyguardManager;
Eric Laurent45c90ce2012-04-24 18:44:22 -0700447 // mVolumeControlStream is set by VolumePanel to temporarily force the stream type which volume
448 // is controlled by Vol keys.
449 private int mVolumeControlStream = -1;
450 private final Object mForceControlStreamLock = new Object();
451 // VolumePanel is currently the only client of forceVolumeControlStream() and runs in system
452 // server process so in theory it is not necessary to monitor the client death.
453 // However it is good to be ready for future evolutions.
454 private ForceControlStreamClient mForceControlStreamClient = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700455 // Used to play ringtones outside system_server
456 private volatile IRingtonePlayer mRingtonePlayer;
Eric Laurent9bc8358d2011-11-18 16:43:31 -0800457
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700458 private int mDeviceOrientation = Configuration.ORIENTATION_UNDEFINED;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700459 private int mDeviceRotation = Surface.ROTATION_0;
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700460
Eric Laurent78472112012-05-21 08:57:21 -0700461 // Request to override default use of A2DP for media.
462 private boolean mBluetoothA2dpEnabled;
463 private final Object mBluetoothA2dpEnabledLock = new Object();
464
Dianne Hackborn632ca412012-06-14 19:34:10 -0700465 // Monitoring of audio routes. Protected by mCurAudioRoutes.
466 final AudioRoutesInfo mCurAudioRoutes = new AudioRoutesInfo();
467 final RemoteCallbackList<IAudioRoutesObserver> mRoutesObservers
468 = new RemoteCallbackList<IAudioRoutesObserver>();
469
Eric Laurent4bbcc652012-09-24 14:26:30 -0700470 // Devices for which the volume is fixed and VolumePanel slider should be disabled
Eric Laurent212532b2014-07-21 15:43:18 -0700471 int mFixedVolumeDevices = AudioSystem.DEVICE_OUT_HDMI |
Eric Laurent4bbcc652012-09-24 14:26:30 -0700472 AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET |
Eric Laurent212532b2014-07-21 15:43:18 -0700473 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET |
474 AudioSystem.DEVICE_OUT_HDMI_ARC |
475 AudioSystem.DEVICE_OUT_SPDIF |
476 AudioSystem.DEVICE_OUT_AUX_LINE;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -0700477 int mFullVolumeDevices = 0;
Eric Laurent4bbcc652012-09-24 14:26:30 -0700478
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700479 // TODO merge orientation and rotation
Eric Laurentd640bd32012-09-28 18:01:48 -0700480 private final boolean mMonitorOrientation;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700481 private final boolean mMonitorRotation;
Eric Laurentd640bd32012-09-28 18:01:48 -0700482
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700483 private boolean mDockAudioMediaEnabled = true;
484
Eric Laurent08ed1b92012-11-05 14:54:12 -0800485 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
486
Eric Laurentfde16d52012-12-03 14:42:39 -0800487 // Used when safe volume warning message display is requested by setStreamVolume(). In this
488 // case, the new requested volume, stream type and device are stored in mPendingVolumeCommand
489 // and used later when/if disableSafeMediaVolume() is called.
490 private StreamVolumeCommand mPendingVolumeCommand;
491
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700492 private PowerManager.WakeLock mAudioEventWakeLock;
493
494 private final MediaFocusControl mMediaFocusControl;
495
John Du5a0cf7a2013-07-19 11:30:34 -0700496 // Reference to BluetoothA2dp to query for AbsoluteVolume.
497 private BluetoothA2dp mA2dp;
seunghwan.hong4fe77952014-10-29 17:43:20 +0900498 // lock always taken synchronized on mConnectedDevices
John Du5a0cf7a2013-07-19 11:30:34 -0700499 private final Object mA2dpAvrcpLock = new Object();
500 // If absolute volume is supported in AVRCP device
501 private boolean mAvrcpAbsVolSupported = false;
502
Jon Eklund318f0fe2014-01-23 17:53:48 -0600503 private AudioOrientationEventListener mOrientationListener;
504
Eric Laurentadbe8bf2014-11-03 18:26:32 -0800505 private static Long mLastDeviceConnectMsgTime = new Long(0);
506
John Spurlock661f2cf2014-11-17 10:29:10 -0500507 private AudioManagerInternal.RingerModeDelegate mRingerModeDelegate;
508
Paul McLean10804eb2015-01-28 11:16:35 -0800509 // Intent "extra" data keys.
510 public static final String CONNECT_INTENT_KEY_PORT_NAME = "portName";
511 public static final String CONNECT_INTENT_KEY_STATE = "state";
512 public static final String CONNECT_INTENT_KEY_ADDRESS = "address";
513 public static final String CONNECT_INTENT_KEY_HAS_PLAYBACK = "hasPlayback";
514 public static final String CONNECT_INTENT_KEY_HAS_CAPTURE = "hasCapture";
515 public static final String CONNECT_INTENT_KEY_HAS_MIDI = "hasMIDI";
516 public static final String CONNECT_INTENT_KEY_DEVICE_CLASS = "class";
517
518 // Defines the format for the connection "address" for ALSA devices
519 public static String makeAlsaAddressString(int card, int device) {
520 return "card=" + card + ";device=" + device + ";";
521 }
522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 ///////////////////////////////////////////////////////////////////////////
524 // Construction
525 ///////////////////////////////////////////////////////////////////////////
526
527 /** @hide */
528 public AudioService(Context context) {
529 mContext = context;
530 mContentResolver = context.getContentResolver();
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700531 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
Eric Laurent212532b2014-07-21 15:43:18 -0700532
John Spurlock61560172015-02-06 19:46:04 -0500533 mPlatformType = AudioSystem.getPlatformType(context);
Jared Suttles59820132009-08-13 21:50:52 -0500534
Jean-Michel Trivic6802222012-04-30 11:15:03 -0700535 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700536 mAudioEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleAudioEvent");
Jean-Michel Trivic6802222012-04-30 11:15:03 -0700537
Eric Laurentbffc3d12012-05-07 17:43:49 -0700538 Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
539 mHasVibrator = vibrator == null ? false : vibrator.hasVibrator();
540
Jared Suttles59820132009-08-13 21:50:52 -0500541 // Intialized volume
Eric Laurent91377de2014-10-10 15:24:04 -0700542 int maxVolume = SystemProperties.getInt("ro.config.vc_call_vol_steps",
543 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
544 if (maxVolume != MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]) {
545 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = maxVolume;
John Spurlock61560172015-02-06 19:46:04 -0500546 AudioSystem.DEFAULT_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = (maxVolume * 3) / 4;
Eric Laurent91377de2014-10-10 15:24:04 -0700547 }
548 maxVolume = SystemProperties.getInt("ro.config.media_vol_steps",
549 MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
550 if (maxVolume != MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]) {
551 MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC] = maxVolume;
John Spurlock61560172015-02-06 19:46:04 -0500552 AudioSystem.DEFAULT_STREAM_VOLUME[AudioSystem.STREAM_MUSIC] = (maxVolume * 3) / 4;
Eric Laurent91377de2014-10-10 15:24:04 -0700553 }
Jared Suttles59820132009-08-13 21:50:52 -0500554
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -0700555 sSoundEffectVolumeDb = context.getResources().getInteger(
Jean-Michel Trivic55b3932012-06-05 11:57:59 -0700556 com.android.internal.R.integer.config_soundEffectVolumeDb);
Eric Laurent25101b02011-02-02 09:33:30 -0800557
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700558 mForcedUseForComm = AudioSystem.FORCE_NONE;
Eric Laurentdd45d012012-10-08 09:04:34 -0700559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 createAudioSystemThread();
Eric Laurentdd45d012012-10-08 09:04:34 -0700561
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700562 mMediaFocusControl = new MediaFocusControl(mAudioHandler.getLooper(),
John Spurlock3346a802014-05-20 16:25:37 -0400563 mContext, mVolumeController, this);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700564
Eric Laurentdfb881f2013-07-18 14:41:39 -0700565 AudioSystem.setErrorCallback(mAudioSystemCallback);
566
John Spurlock5e783732015-02-19 10:28:59 -0500567 boolean cameraSoundForced = readCameraSoundForced();
Eric Laurentdd45d012012-10-08 09:04:34 -0700568 mCameraSoundForced = new Boolean(cameraSoundForced);
569 sendMsg(mAudioHandler,
570 MSG_SET_FORCE_USE,
571 SENDMSG_QUEUE,
572 AudioSystem.FOR_SYSTEM,
573 cameraSoundForced ?
574 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE,
575 null,
576 0);
577
Eric Laurent05274f32012-11-29 12:48:18 -0800578 mSafeMediaVolumeState = new Integer(Settings.Global.getInt(mContentResolver,
579 Settings.Global.AUDIO_SAFE_VOLUME_STATE,
580 SAFE_MEDIA_VOLUME_NOT_CONFIGURED));
581 // The default safe volume index read here will be replaced by the actual value when
582 // the mcc is read by onConfigureSafeVolume()
583 mSafeMediaVolumeIndex = mContext.getResources().getInteger(
584 com.android.internal.R.integer.config_safe_media_volume_index) * 10;
585
Eric Laurent83a017b2013-03-19 18:15:31 -0700586 mUseFixedVolume = mContext.getResources().getBoolean(
587 com.android.internal.R.bool.config_useFixedVolume);
588
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700589 // must be called before readPersistedSettings() which needs a valid mStreamVolumeAlias[]
590 // array initialized by updateStreamVolumeAlias()
591 updateStreamVolumeAlias(false /*updateVolumes*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 readPersistedSettings();
Eric Laurentc1d41662011-07-19 11:21:13 -0700593 mSettingsObserver = new SettingsObserver();
Eric Laurenta553c252009-07-17 12:17:14 -0700594 createStreamStates();
Eric Laurent9f103de2011-09-08 15:04:23 -0700595
Glenn Kastenfd116ad2013-07-12 17:10:39 -0700596 readAndSetLowRamDevice();
Eric Laurent3891c4c2010-04-20 09:40:57 -0700597
598 // Call setRingerModeInt() to apply correct mute
599 // state on streams affected by ringer mode.
600 mRingerModeMutedStreams = 0;
John Spurlock661f2cf2014-11-17 10:29:10 -0500601 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent3891c4c2010-04-20 09:40:57 -0700602
Eric Laurenta553c252009-07-17 12:17:14 -0700603 // Register for device connection intent broadcasts.
604 IntentFilter intentFilter =
Eric Laurentb1fbaac2012-05-29 09:24:28 -0700605 new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700606 intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
607 intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
Eric Laurent950e8cb2011-10-13 08:57:54 -0700608 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
609 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
Eric Laurentbc0fab1f2012-09-19 11:24:41 -0700610 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Paul McLeanc837a452014-04-09 09:04:43 -0700611 intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700612
Eric Laurentd640bd32012-09-28 18:01:48 -0700613 intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700614 // TODO merge orientation and rotation
Eric Laurentd640bd32012-09-28 18:01:48 -0700615 mMonitorOrientation = SystemProperties.getBoolean("ro.audio.monitorOrientation", false);
616 if (mMonitorOrientation) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700617 Log.v(TAG, "monitoring device orientation");
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700618 // initialize orientation in AudioSystem
619 setOrientationForAudioSystem();
620 }
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700621 mMonitorRotation = SystemProperties.getBoolean("ro.audio.monitorRotation", false);
622 if (mMonitorRotation) {
623 mDeviceRotation = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE))
624 .getDefaultDisplay().getRotation();
625 Log.v(TAG, "monitoring device rotation, initial=" + mDeviceRotation);
Jon Eklund318f0fe2014-01-23 17:53:48 -0600626
627 mOrientationListener = new AudioOrientationEventListener(mContext);
628 mOrientationListener.enable();
629
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700630 // initialize rotation in AudioSystem
631 setRotationForAudioSystem();
632 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700633
Eric Laurenta553c252009-07-17 12:17:14 -0700634 context.registerReceiver(mReceiver, intentFilter);
Jared Suttles59820132009-08-13 21:50:52 -0500635
RoboErik0dac35a2014-08-12 15:48:49 -0700636 LocalServices.addService(AudioManagerInternal.class, new AudioServiceInternal());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 }
638
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700639 public void systemReady() {
640 sendMsg(mAudioHandler, MSG_SYSTEM_READY, SENDMSG_QUEUE,
641 0, 0, null, 0);
642 }
643
644 public void onSystemReady() {
645 mSystemReady = true;
646 sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_QUEUE,
647 0, 0, null, 0);
648
649 mKeyguardManager =
650 (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
651 mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR;
652 resetBluetoothSco();
653 getBluetoothHeadset();
654 //FIXME: this is to maintain compatibility with deprecated intent
655 // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
656 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
657 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
658 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
659 sendStickyBroadcastToAll(newIntent);
660
661 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
662 if (adapter != null) {
663 adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
664 BluetoothProfile.A2DP);
665 }
666
Eric Laurent212532b2014-07-21 15:43:18 -0700667 mHdmiManager =
Wonsik Kim7f4342e2014-07-20 23:04:59 +0900668 (HdmiControlManager) mContext.getSystemService(Context.HDMI_CONTROL_SERVICE);
Eric Laurent212532b2014-07-21 15:43:18 -0700669 if (mHdmiManager != null) {
670 synchronized (mHdmiManager) {
671 mHdmiTvClient = mHdmiManager.getTvClient();
Jungshik Jangc9ff9682014-09-15 17:41:06 +0900672 if (mHdmiTvClient != null) {
673 mFixedVolumeDevices &= ~AudioSystem.DEVICE_ALL_HDMI_SYSTEM_AUDIO_AND_SPEAKER;
674 }
Eric Laurent212532b2014-07-21 15:43:18 -0700675 mHdmiPlaybackClient = mHdmiManager.getPlaybackClient();
676 mHdmiCecSink = false;
677 }
678 }
Wonsik Kim7f4342e2014-07-20 23:04:59 +0900679
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700680 sendMsg(mAudioHandler,
681 MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED,
682 SENDMSG_REPLACE,
683 0,
684 0,
685 null,
686 SAFE_VOLUME_CONFIGURE_TIMEOUT_MS);
Jean-Michel Trivi873cc452014-09-11 17:25:09 -0700687
688 StreamOverride.init(mContext);
John Spurlockcdb57ae2015-02-11 19:04:11 -0500689 mControllerService.init();
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700690 }
691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 private void createAudioSystemThread() {
693 mAudioSystemThread = new AudioSystemThread();
694 mAudioSystemThread.start();
695 waitForAudioHandlerCreation();
696 }
697
698 /** Waits for the volume handler to be created by the other thread. */
699 private void waitForAudioHandlerCreation() {
700 synchronized(this) {
701 while (mAudioHandler == null) {
702 try {
703 // Wait for mAudioHandler to be set by the other thread
704 wait();
705 } catch (InterruptedException e) {
706 Log.e(TAG, "Interrupted while waiting on volume handler.");
707 }
708 }
709 }
710 }
711
Eric Laurent24482012012-05-10 09:41:17 -0700712 private void checkAllAliasStreamVolumes() {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -0700713 synchronized (VolumeStreamState.class) {
714 int numStreamTypes = AudioSystem.getNumStreamTypes();
715 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
716 if (streamType != mStreamVolumeAlias[streamType]) {
717 mStreamStates[streamType].
Eric Laurent42b041e2013-03-29 11:36:03 -0700718 setAllIndexes(mStreamStates[mStreamVolumeAlias[streamType]]);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -0700719 }
720 // apply stream volume
RoboErik4197cb62015-01-21 15:45:32 -0800721 if (!mStreamStates[streamType].mIsMuted) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -0700722 mStreamStates[streamType].applyAllVolumes();
723 }
Eric Laurent24482012012-05-10 09:41:17 -0700724 }
725 }
726 }
727
Eric Laurent212532b2014-07-21 15:43:18 -0700728 private void checkAllFixedVolumeDevices()
729 {
730 int numStreamTypes = AudioSystem.getNumStreamTypes();
731 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
732 mStreamStates[streamType].checkFixedVolumeDevices();
733 }
734 }
735
Jean-Michel Triviba5270b2014-10-01 17:49:29 -0700736 private void checkAllFixedVolumeDevices(int streamType) {
737 mStreamStates[streamType].checkFixedVolumeDevices();
738 }
739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 private void createStreamStates() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 int numStreamTypes = AudioSystem.getNumStreamTypes();
742 VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
743
744 for (int i = 0; i < numStreamTypes; i++) {
Eric Laurent6d517662012-04-23 18:42:39 -0700745 streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[mStreamVolumeAlias[i]], i);
Eric Laurenta553c252009-07-17 12:17:14 -0700746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747
Eric Laurent212532b2014-07-21 15:43:18 -0700748 checkAllFixedVolumeDevices();
Eric Laurent24482012012-05-10 09:41:17 -0700749 checkAllAliasStreamVolumes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 }
751
Eric Laurentbffc3d12012-05-07 17:43:49 -0700752 private void dumpStreamStates(PrintWriter pw) {
753 pw.println("\nStream volumes (device: index)");
754 int numStreamTypes = AudioSystem.getNumStreamTypes();
755 for (int i = 0; i < numStreamTypes; i++) {
John Spurlock61560172015-02-06 19:46:04 -0500756 pw.println("- " + AudioSystem.STREAM_NAMES[i] + ":");
Eric Laurentbffc3d12012-05-07 17:43:49 -0700757 mStreamStates[i].dump(pw);
758 pw.println("");
759 }
Eric Laurentdd45d012012-10-08 09:04:34 -0700760 pw.print("\n- mute affected streams = 0x");
761 pw.println(Integer.toHexString(mMuteAffectedStreams));
Eric Laurentbffc3d12012-05-07 17:43:49 -0700762 }
763
Eric Laurent6d517662012-04-23 18:42:39 -0700764 private void updateStreamVolumeAlias(boolean updateVolumes) {
765 int dtmfStreamAlias;
Eric Laurent212532b2014-07-21 15:43:18 -0700766
767 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -0500768 case AudioSystem.PLATFORM_VOICE:
Eric Laurent212532b2014-07-21 15:43:18 -0700769 mStreamVolumeAlias = STREAM_VOLUME_ALIAS_VOICE;
Eric Laurent6d517662012-04-23 18:42:39 -0700770 dtmfStreamAlias = AudioSystem.STREAM_RING;
Eric Laurent212532b2014-07-21 15:43:18 -0700771 break;
John Spurlock61560172015-02-06 19:46:04 -0500772 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -0700773 mStreamVolumeAlias = STREAM_VOLUME_ALIAS_TELEVISION;
774 dtmfStreamAlias = AudioSystem.STREAM_MUSIC;
775 break;
776 default:
777 mStreamVolumeAlias = STREAM_VOLUME_ALIAS_DEFAULT;
Eric Laurent6d517662012-04-23 18:42:39 -0700778 dtmfStreamAlias = AudioSystem.STREAM_MUSIC;
779 }
Eric Laurent212532b2014-07-21 15:43:18 -0700780
781 if (isPlatformTelevision()) {
782 mRingerModeAffectedStreams = 0;
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700783 } else {
Eric Laurent212532b2014-07-21 15:43:18 -0700784 if (isInCommunication()) {
785 dtmfStreamAlias = AudioSystem.STREAM_VOICE_CALL;
786 mRingerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_DTMF);
787 } else {
788 mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_DTMF);
789 }
Eric Laurent6d517662012-04-23 18:42:39 -0700790 }
Eric Laurent212532b2014-07-21 15:43:18 -0700791
Eric Laurent6d517662012-04-23 18:42:39 -0700792 mStreamVolumeAlias[AudioSystem.STREAM_DTMF] = dtmfStreamAlias;
793 if (updateVolumes) {
Eric Laurent42b041e2013-03-29 11:36:03 -0700794 mStreamStates[AudioSystem.STREAM_DTMF].setAllIndexes(mStreamStates[dtmfStreamAlias]);
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700795 // apply stream mute states according to new value of mRingerModeAffectedStreams
John Spurlock661f2cf2014-11-17 10:29:10 -0500796 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent6d517662012-04-23 18:42:39 -0700797 sendMsg(mAudioHandler,
798 MSG_SET_ALL_VOLUMES,
799 SENDMSG_QUEUE,
800 0,
801 0,
802 mStreamStates[AudioSystem.STREAM_DTMF], 0);
803 }
804 }
805
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700806 private void readDockAudioSettings(ContentResolver cr)
807 {
808 mDockAudioMediaEnabled = Settings.Global.getInt(
Eric Laurent5ba0ffa02012-10-29 12:31:09 -0700809 cr, Settings.Global.DOCK_AUDIO_MEDIA_ENABLED, 0) == 1;
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700810
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700811 sendMsg(mAudioHandler,
812 MSG_SET_FORCE_USE,
813 SENDMSG_QUEUE,
814 AudioSystem.FOR_DOCK,
815 mDockAudioMediaEnabled ?
816 AudioSystem.FORCE_ANALOG_DOCK : AudioSystem.FORCE_NONE,
817 null,
818 0);
819 }
820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 private void readPersistedSettings() {
822 final ContentResolver cr = mContentResolver;
823
Eric Laurentbffc3d12012-05-07 17:43:49 -0700824 int ringerModeFromSettings =
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -0700825 Settings.Global.getInt(
826 cr, Settings.Global.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
Eric Laurentbffc3d12012-05-07 17:43:49 -0700827 int ringerMode = ringerModeFromSettings;
Eric Laurent72668b22011-07-19 16:04:27 -0700828 // sanity check in case the settings are restored from a device with incompatible
829 // ringer modes
John Spurlock97559372014-10-24 16:27:36 -0400830 if (!isValidRingerMode(ringerMode)) {
Glenn Kastenba195eb2011-12-13 09:30:40 -0800831 ringerMode = AudioManager.RINGER_MODE_NORMAL;
Eric Laurentbffc3d12012-05-07 17:43:49 -0700832 }
833 if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) {
834 ringerMode = AudioManager.RINGER_MODE_SILENT;
835 }
836 if (ringerMode != ringerModeFromSettings) {
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -0700837 Settings.Global.putInt(cr, Settings.Global.MODE_RINGER, ringerMode);
Glenn Kastenba195eb2011-12-13 09:30:40 -0800838 }
Eric Laurent212532b2014-07-21 15:43:18 -0700839 if (mUseFixedVolume || isPlatformTelevision()) {
Eric Laurent83a017b2013-03-19 18:15:31 -0700840 ringerMode = AudioManager.RINGER_MODE_NORMAL;
841 }
Glenn Kastenba195eb2011-12-13 09:30:40 -0800842 synchronized(mSettingsLock) {
843 mRingerMode = ringerMode;
John Spurlock661f2cf2014-11-17 10:29:10 -0500844 if (mRingerModeExternal == -1) {
845 mRingerModeExternal = mRingerMode;
846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847
Eric Laurentdd45d012012-10-08 09:04:34 -0700848 // System.VIBRATE_ON is not used any more but defaults for mVibrateSetting
849 // are still needed while setVibrateSetting() and getVibrateSetting() are being
850 // deprecated.
John Spurlock61560172015-02-06 19:46:04 -0500851 mVibrateSetting = AudioSystem.getValueForVibrateSetting(0,
Eric Laurentdd45d012012-10-08 09:04:34 -0700852 AudioManager.VIBRATE_TYPE_NOTIFICATION,
853 mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT
854 : AudioManager.VIBRATE_SETTING_OFF);
John Spurlock61560172015-02-06 19:46:04 -0500855 mVibrateSetting = AudioSystem.getValueForVibrateSetting(mVibrateSetting,
Eric Laurentdd45d012012-10-08 09:04:34 -0700856 AudioManager.VIBRATE_TYPE_RINGER,
857 mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT
858 : AudioManager.VIBRATE_SETTING_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700860 updateRingerModeAffectedStreams();
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700861 readDockAudioSettings(cr);
Eric Laurent402f7f22011-02-04 12:30:32 -0800862 }
Eric Laurentc1d41662011-07-19 11:21:13 -0700863
Eric Laurentbc0fab1f2012-09-19 11:24:41 -0700864 mMuteAffectedStreams = System.getIntForUser(cr,
John Spurlock61560172015-02-06 19:46:04 -0500865 System.MUTE_STREAMS_AFFECTED, AudioSystem.DEFAULT_MUTE_STREAMS_AFFECTED,
John Spurlock24c05182015-02-05 12:30:36 -0500866 UserHandle.USER_CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867
Eric Laurentbc0fab1f2012-09-19 11:24:41 -0700868 boolean masterMute = System.getIntForUser(cr, System.VOLUME_MASTER_MUTE,
John Spurlockee5ad722015-03-03 16:17:21 -0500869 0, UserHandle.USER_CURRENT) == 1;
Eric Laurent83a017b2013-03-19 18:15:31 -0700870 if (mUseFixedVolume) {
871 masterMute = false;
872 AudioSystem.setMasterVolume(1.0f);
873 }
Justin Koh57978ed2012-04-03 17:37:58 -0700874 AudioSystem.setMasterMute(masterMute);
875 broadcastMasterMuteStatus(masterMute);
876
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400877 boolean microphoneMute =
878 System.getIntForUser(cr, System.MICROPHONE_MUTE, 0, UserHandle.USER_CURRENT) == 1;
879 AudioSystem.muteMicrophone(microphoneMute);
880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 // Each stream will read its own persisted settings
882
John Spurlockbcc10872014-11-28 15:29:21 -0500883 // Broadcast the sticky intents
884 broadcastRingerMode(AudioManager.RINGER_MODE_CHANGED_ACTION, mRingerModeExternal);
885 broadcastRingerMode(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION, mRingerMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886
887 // Broadcast vibrate settings
888 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
889 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
Jean-Michel Trivid589fea2011-04-15 11:28:10 -0700890
John Spurlock33f4e042014-07-11 13:10:58 -0400891 // Load settings for the volume controller
892 mVolumeController.loadSettings(cr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894
Eric Laurenta553c252009-07-17 12:17:14 -0700895 private int rescaleIndex(int index, int srcStream, int dstStream) {
896 return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898
Jon Eklund318f0fe2014-01-23 17:53:48 -0600899 private class AudioOrientationEventListener
900 extends OrientationEventListener {
901 public AudioOrientationEventListener(Context context) {
902 super(context);
903 }
904
905 @Override
906 public void onOrientationChanged(int orientation) {
907 //Even though we're responding to phone orientation events,
908 //use display rotation so audio stays in sync with video/dialogs
909 int newRotation = ((WindowManager) mContext.getSystemService(
910 Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
911 if (newRotation != mDeviceRotation) {
912 mDeviceRotation = newRotation;
913 setRotationForAudioSystem();
914 }
915 }
916 }
917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 ///////////////////////////////////////////////////////////////////////////
919 // IPC methods
920 ///////////////////////////////////////////////////////////////////////////
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 /** @see AudioManager#adjustVolume(int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700922 public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags,
923 String callingPackage) {
RoboErik272e1612014-09-05 11:39:29 -0700924 adjustSuggestedStreamVolume(direction, suggestedStreamType, flags, callingPackage,
925 Binder.getCallingUid());
926 }
927
928 private void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags,
929 String callingPackage, int uid) {
John Spurlockae641c92014-06-30 18:11:40 -0400930 if (DEBUG_VOL) Log.d(TAG, "adjustSuggestedStreamVolume() stream="+suggestedStreamType
931 + ", flags=" + flags);
Eric Laurent402f7f22011-02-04 12:30:32 -0800932 int streamType;
RoboErik4197cb62015-01-21 15:45:32 -0800933 boolean isMute = isMuteAdjust(direction);
Eric Laurent45c90ce2012-04-24 18:44:22 -0700934 if (mVolumeControlStream != -1) {
935 streamType = mVolumeControlStream;
Eric Laurent402f7f22011-02-04 12:30:32 -0800936 } else {
937 streamType = getActiveStreamType(suggestedStreamType);
938 }
John Spurlock33f4e042014-07-11 13:10:58 -0400939 final int resolvedStream = mStreamVolumeAlias[streamType];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940
RoboErik2811dd32014-08-12 09:48:13 -0700941 // Play sounds on STREAM_RING only.
942 if ((flags & AudioManager.FLAG_PLAY_SOUND) != 0 &&
John Spurlock33f4e042014-07-11 13:10:58 -0400943 resolvedStream != AudioSystem.STREAM_RING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 flags &= ~AudioManager.FLAG_PLAY_SOUND;
945 }
946
John Spurlock33f4e042014-07-11 13:10:58 -0400947 // For notifications/ring, show the ui before making any adjustments
RoboErik4197cb62015-01-21 15:45:32 -0800948 // Don't suppress mute/unmute requests
949 if (mVolumeController.suppressAdjustment(resolvedStream, flags, isMute)) {
John Spurlock33f4e042014-07-11 13:10:58 -0400950 direction = 0;
951 flags &= ~AudioManager.FLAG_PLAY_SOUND;
952 flags &= ~AudioManager.FLAG_VIBRATE;
953 if (DEBUG_VOL) Log.d(TAG, "Volume controller suppressed adjustment");
954 }
955
RoboErik272e1612014-09-05 11:39:29 -0700956 adjustStreamVolume(streamType, direction, flags, callingPackage, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
958
959 /** @see AudioManager#adjustStreamVolume(int, int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700960 public void adjustStreamVolume(int streamType, int direction, int flags,
961 String callingPackage) {
RoboErik0dac35a2014-08-12 15:48:49 -0700962 adjustStreamVolume(streamType, direction, flags, callingPackage, Binder.getCallingUid());
963 }
964
965 private void adjustStreamVolume(int streamType, int direction, int flags,
966 String callingPackage, int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -0700967 if (mUseFixedVolume) {
968 return;
969 }
John Spurlockae641c92014-06-30 18:11:40 -0400970 if (DEBUG_VOL) Log.d(TAG, "adjustStreamVolume() stream="+streamType+", dir="+direction
971 + ", flags="+flags);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 ensureValidDirection(direction);
974 ensureValidStreamType(streamType);
975
RoboErik4197cb62015-01-21 15:45:32 -0800976 boolean isMuteAdjust = isMuteAdjust(direction);
977
John Spurlock3ce37252015-02-17 13:20:45 -0500978 if (isMuteAdjust && !isStreamAffectedByMute(streamType)) {
979 return;
980 }
981
Eric Laurent96a33d12011-11-08 10:31:57 -0800982 // use stream type alias here so that streams with same alias have the same behavior,
983 // including with regard to silent mode control (e.g the use of STREAM_RING below and in
984 // checkForRingerModeChange() in place of STREAM_RING or STREAM_NOTIFICATION)
Eric Laurent6d517662012-04-23 18:42:39 -0700985 int streamTypeAlias = mStreamVolumeAlias[streamType];
RoboErik4197cb62015-01-21 15:45:32 -0800986
Eric Laurentb024c302011-10-14 17:19:27 -0700987 VolumeStreamState streamState = mStreamStates[streamTypeAlias];
Eric Laurent9bc8358d2011-11-18 16:43:31 -0800988
989 final int device = getDeviceForStream(streamTypeAlias);
Eric Laurent3ef75492012-11-28 12:12:23 -0800990
Eric Laurent42b041e2013-03-29 11:36:03 -0700991 int aliasIndex = streamState.getIndex(device);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 boolean adjustVolume = true;
Eric Laurent3ef75492012-11-28 12:12:23 -0800993 int step;
Eric Laurent24482012012-05-10 09:41:17 -0700994
Matthew Xiec9d1d5f2013-09-12 00:32:22 -0700995 // skip a2dp absolute volume control request when the device
996 // is not an a2dp device
997 if ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) == 0 &&
998 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) != 0) {
999 return;
1000 }
1001
John Spurlock59dc9c12015-03-02 11:20:15 -05001002 if (mAppOps.noteOp(STREAM_VOLUME_OPS[streamTypeAlias], uid, callingPackage)
RoboErik0dac35a2014-08-12 15:48:49 -07001003 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001004 return;
1005 }
1006
Eric Laurentfde16d52012-12-03 14:42:39 -08001007 // reset any pending volume command
1008 synchronized (mSafeMediaVolumeState) {
1009 mPendingVolumeCommand = null;
1010 }
1011
Eric Laurent3ef75492012-11-28 12:12:23 -08001012 flags &= ~AudioManager.FLAG_FIXED_VOLUME;
1013 if ((streamTypeAlias == AudioSystem.STREAM_MUSIC) &&
1014 ((device & mFixedVolumeDevices) != 0)) {
1015 flags |= AudioManager.FLAG_FIXED_VOLUME;
1016
1017 // Always toggle between max safe volume and 0 for fixed volume devices where safe
1018 // volume is enforced, and max and 0 for the others.
1019 // This is simulated by stepping by the full allowed volume range
1020 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE &&
1021 (device & mSafeMediaVolumeDevices) != 0) {
1022 step = mSafeMediaVolumeIndex;
1023 } else {
1024 step = streamState.getMaxIndex();
1025 }
1026 if (aliasIndex != 0) {
1027 aliasIndex = step;
1028 }
1029 } else {
1030 // convert one UI step (+/-1) into a number of internal units on the stream alias
1031 step = rescaleIndex(10, streamType, streamTypeAlias);
1032 }
1033
Eric Laurent42b041e2013-03-29 11:36:03 -07001034 // If either the client forces allowing ringer modes for this adjustment,
1035 // or the stream type is one that is affected by ringer modes
1036 if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
John Spurlockee5ad722015-03-03 16:17:21 -05001037 (streamTypeAlias == getUiSoundsStreamType())) {
John Spurlock661f2cf2014-11-17 10:29:10 -05001038 int ringerMode = getRingerModeInternal();
Eric Laurent42b041e2013-03-29 11:36:03 -07001039 // do not vibrate if already in vibrate mode
1040 if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
1041 flags &= ~AudioManager.FLAG_VIBRATE;
Eric Laurent3ef75492012-11-28 12:12:23 -08001042 }
RoboErik5452e252015-02-06 15:33:53 -08001043 // Check if the ringer mode handles this adjustment. If it does we don't
1044 // need to adjust the volume further.
1045 final int result = checkForRingerModeChange(aliasIndex, direction, step, streamState.mIsMuted);
John Spurlocka11b4af2014-06-01 11:52:23 -04001046 adjustVolume = (result & FLAG_ADJUST_VOLUME) != 0;
1047 // If suppressing a volume adjustment in silent mode, display the UI hint
1048 if ((result & AudioManager.FLAG_SHOW_SILENT_HINT) != 0) {
1049 flags |= AudioManager.FLAG_SHOW_SILENT_HINT;
1050 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001051 // If suppressing a volume down adjustment in vibrate mode, display the UI hint
1052 if ((result & AudioManager.FLAG_SHOW_VIBRATE_HINT) != 0) {
1053 flags |= AudioManager.FLAG_SHOW_VIBRATE_HINT;
1054 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001055 }
Eric Laurent3ef75492012-11-28 12:12:23 -08001056
Eric Laurent42b041e2013-03-29 11:36:03 -07001057 int oldIndex = mStreamStates[streamType].getIndex(device);
Eric Laurent3ef75492012-11-28 12:12:23 -08001058
Eric Laurent42b041e2013-03-29 11:36:03 -07001059 if (adjustVolume && (direction != AudioManager.ADJUST_SAME)) {
RoboErik5452e252015-02-06 15:33:53 -08001060 mAudioHandler.removeMessages(MSG_UNMUTE_STREAM);
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001061
John Du5a0cf7a2013-07-19 11:30:34 -07001062 // Check if volume update should be send to AVRCP
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001063 if (streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1064 (device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
1065 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) {
1066 synchronized (mA2dpAvrcpLock) {
1067 if (mA2dp != null && mAvrcpAbsVolSupported) {
1068 mA2dp.adjustAvrcpAbsoluteVolume(direction);
1069 }
John Du5a0cf7a2013-07-19 11:30:34 -07001070 }
1071 }
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001072
RoboErik4197cb62015-01-21 15:45:32 -08001073 if (isMuteAdjust) {
1074 boolean state;
1075 if (direction == AudioManager.ADJUST_TOGGLE_MUTE) {
1076 state = !streamState.mIsMuted;
1077 } else {
1078 state = direction == AudioManager.ADJUST_MUTE;
1079 }
1080 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1081 setSystemAudioMute(state);
1082 }
1083 for (int stream = 0; stream < mStreamStates.length; stream++) {
1084 if (streamTypeAlias == mStreamVolumeAlias[stream]) {
1085 mStreamStates[stream].mute(state);
RoboErik4197cb62015-01-21 15:45:32 -08001086 }
1087 }
1088 } else if ((direction == AudioManager.ADJUST_RAISE) &&
Eric Laurent42b041e2013-03-29 11:36:03 -07001089 !checkSafeMediaVolume(streamTypeAlias, aliasIndex + step, device)) {
RoboErik4197cb62015-01-21 15:45:32 -08001090 Log.e(TAG, "adjustStreamVolume() safe volume index = " + oldIndex);
John Spurlock3346a802014-05-20 16:25:37 -04001091 mVolumeController.postDisplaySafeVolumeWarning(flags);
RoboErik4197cb62015-01-21 15:45:32 -08001092 } else if (streamState.adjustIndex(direction * step, device) || streamState.mIsMuted) {
1093 // Post message to set system volume (it in turn will post a
1094 // message to persist).
1095 if (streamState.mIsMuted) {
1096 // Unmute the stream if it was previously muted
RoboErik5452e252015-02-06 15:33:53 -08001097 if (direction == AudioManager.ADJUST_RAISE) {
1098 // unmute immediately for volume up
1099 streamState.mute(false);
1100 } else if (direction == AudioManager.ADJUST_LOWER) {
1101 sendMsg(mAudioHandler, MSG_UNMUTE_STREAM, SENDMSG_QUEUE,
1102 streamTypeAlias, flags, null, UNMUTE_STREAM_DELAY);
1103 }
RoboErik4197cb62015-01-21 15:45:32 -08001104 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001105 sendMsg(mAudioHandler,
1106 MSG_SET_DEVICE_VOLUME,
1107 SENDMSG_QUEUE,
1108 device,
1109 0,
1110 streamState,
1111 0);
Eric Laurent4bbcc652012-09-24 14:26:30 -07001112 }
Jungshik Jang41d97462014-06-30 22:26:29 +09001113
RoboErik4197cb62015-01-21 15:45:32 -08001114 // Check if volume update should be sent to Hdmi system audio.
Jungshik Jang41d97462014-06-30 22:26:29 +09001115 int newIndex = mStreamStates[streamType].getIndex(device);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001116 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1117 setSystemAudioVolume(oldIndex, newIndex, getStreamMaxVolume(streamType), flags);
1118 }
Eric Laurent212532b2014-07-21 15:43:18 -07001119 if (mHdmiManager != null) {
1120 synchronized (mHdmiManager) {
Eric Laurent212532b2014-07-21 15:43:18 -07001121 // mHdmiCecSink true => mHdmiPlaybackClient != null
1122 if (mHdmiCecSink &&
1123 streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1124 oldIndex != newIndex) {
1125 synchronized (mHdmiPlaybackClient) {
1126 int keyCode = (direction == -1) ? KeyEvent.KEYCODE_VOLUME_DOWN :
RoboErik4197cb62015-01-21 15:45:32 -08001127 KeyEvent.KEYCODE_VOLUME_UP;
Eric Laurent212532b2014-07-21 15:43:18 -07001128 mHdmiPlaybackClient.sendKeyEvent(keyCode, true);
1129 mHdmiPlaybackClient.sendKeyEvent(keyCode, false);
1130 }
Jungshik Jang41d97462014-06-30 22:26:29 +09001131 }
1132 }
1133 }
Eric Laurent4bbcc652012-09-24 14:26:30 -07001134 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001135 int index = mStreamStates[streamType].getIndex(device);
Eric Laurent25101b02011-02-02 09:33:30 -08001136 sendVolumeUpdate(streamType, oldIndex, index, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 }
1138
RoboErik5452e252015-02-06 15:33:53 -08001139 // Called after a delay when volume down is pressed while muted
1140 private void onUnmuteStream(int stream, int flags) {
1141 VolumeStreamState streamState = mStreamStates[stream];
1142 streamState.mute(false);
1143
1144 final int device = getDeviceForStream(stream);
1145 final int index = mStreamStates[stream].getIndex(device);
1146 sendVolumeUpdate(stream, index, index, flags);
1147 }
1148
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001149 private void setSystemAudioVolume(int oldVolume, int newVolume, int maxVolume, int flags) {
1150 if (mHdmiManager == null
1151 || mHdmiTvClient == null
1152 || oldVolume == newVolume
1153 || (flags & AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME) != 0) return;
1154
1155 // Sets the audio volume of AVR when we are in system audio mode. The new volume info
1156 // is tranformed to HDMI-CEC commands and passed through CEC bus.
1157 synchronized (mHdmiManager) {
1158 if (!mHdmiSystemAudioSupported) return;
1159 synchronized (mHdmiTvClient) {
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001160 final long token = Binder.clearCallingIdentity();
1161 try {
Jinsuk Kim7a9ba422015-02-16 16:47:38 +09001162 mHdmiTvClient.setSystemAudioVolume(oldVolume, newVolume, maxVolume);
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001163 } finally {
1164 Binder.restoreCallingIdentity(token);
1165 }
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001166 }
1167 }
1168 }
1169
Eric Laurentfde16d52012-12-03 14:42:39 -08001170 // StreamVolumeCommand contains the information needed to defer the process of
1171 // setStreamVolume() in case the user has to acknowledge the safe volume warning message.
1172 class StreamVolumeCommand {
1173 public final int mStreamType;
1174 public final int mIndex;
1175 public final int mFlags;
1176 public final int mDevice;
Eric Laurent9ce379a2010-02-16 06:00:26 -08001177
Eric Laurentfde16d52012-12-03 14:42:39 -08001178 StreamVolumeCommand(int streamType, int index, int flags, int device) {
1179 mStreamType = streamType;
1180 mIndex = index;
1181 mFlags = flags;
1182 mDevice = device;
Eric Laurentb024c302011-10-14 17:19:27 -07001183 }
John Spurlock35134602014-07-24 18:10:48 -04001184
1185 @Override
1186 public String toString() {
1187 return new StringBuilder().append("{streamType=").append(mStreamType).append(",index=")
1188 .append(mIndex).append(",flags=").append(mFlags).append(",device=")
1189 .append(mDevice).append('}').toString();
1190 }
Eric Laurentfde16d52012-12-03 14:42:39 -08001191 };
Eric Laurent3ef75492012-11-28 12:12:23 -08001192
Eric Laurentfde16d52012-12-03 14:42:39 -08001193 private void onSetStreamVolume(int streamType, int index, int flags, int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07001194 setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, false);
John Spurlockee5ad722015-03-03 16:17:21 -05001195 // setting volume on ui sounds stream type also controls silent mode
Eric Laurent3ef75492012-11-28 12:12:23 -08001196 if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
John Spurlockee5ad722015-03-03 16:17:21 -05001197 (mStreamVolumeAlias[streamType] == getUiSoundsStreamType())) {
Eric Laurent3ef75492012-11-28 12:12:23 -08001198 int newRingerMode;
1199 if (index == 0) {
1200 newRingerMode = mHasVibrator ? AudioManager.RINGER_MODE_VIBRATE
John Spurlock86005342014-05-23 11:58:00 -04001201 : VOLUME_SETS_RINGER_MODE_SILENT ? AudioManager.RINGER_MODE_SILENT
1202 : AudioManager.RINGER_MODE_NORMAL;
Eric Laurent3ef75492012-11-28 12:12:23 -08001203 } else {
1204 newRingerMode = AudioManager.RINGER_MODE_NORMAL;
1205 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001206 setRingerMode(newRingerMode, TAG + ".onSetStreamVolume", false /*external*/);
Eric Laurent3ef75492012-11-28 12:12:23 -08001207 }
Eric Laurentfde16d52012-12-03 14:42:39 -08001208 }
1209
1210 /** @see AudioManager#setStreamVolume(int, int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001211 public void setStreamVolume(int streamType, int index, int flags, String callingPackage) {
RoboErik0dac35a2014-08-12 15:48:49 -07001212 setStreamVolume(streamType, index, flags, callingPackage, Binder.getCallingUid());
1213 }
1214
1215 private void setStreamVolume(int streamType, int index, int flags, String callingPackage,
1216 int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001217 if (mUseFixedVolume) {
1218 return;
1219 }
1220
Eric Laurentfde16d52012-12-03 14:42:39 -08001221 ensureValidStreamType(streamType);
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001222 int streamTypeAlias = mStreamVolumeAlias[streamType];
1223 VolumeStreamState streamState = mStreamStates[streamTypeAlias];
Eric Laurentfde16d52012-12-03 14:42:39 -08001224
1225 final int device = getDeviceForStream(streamType);
1226 int oldIndex;
1227
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001228 // skip a2dp absolute volume control request when the device
1229 // is not an a2dp device
1230 if ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) == 0 &&
1231 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) != 0) {
1232 return;
1233 }
1234
John Spurlock59dc9c12015-03-02 11:20:15 -05001235 if (mAppOps.noteOp(STREAM_VOLUME_OPS[streamTypeAlias], uid, callingPackage)
RoboErik0dac35a2014-08-12 15:48:49 -07001236 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001237 return;
1238 }
1239
Eric Laurentfde16d52012-12-03 14:42:39 -08001240 synchronized (mSafeMediaVolumeState) {
1241 // reset any pending volume command
1242 mPendingVolumeCommand = null;
1243
Eric Laurent42b041e2013-03-29 11:36:03 -07001244 oldIndex = streamState.getIndex(device);
Eric Laurentfde16d52012-12-03 14:42:39 -08001245
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001246 index = rescaleIndex(index * 10, streamType, streamTypeAlias);
Eric Laurentfde16d52012-12-03 14:42:39 -08001247
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001248 if (streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1249 (device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
1250 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) {
1251 synchronized (mA2dpAvrcpLock) {
1252 if (mA2dp != null && mAvrcpAbsVolSupported) {
Zhihai Xu2f4a2b12014-01-10 16:44:39 -08001253 mA2dp.setAvrcpAbsoluteVolume(index / 10);
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001254 }
John Du5a0cf7a2013-07-19 11:30:34 -07001255 }
1256 }
1257
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001258 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1259 setSystemAudioVolume(oldIndex, index, getStreamMaxVolume(streamType), flags);
Jungshik Jang41d97462014-06-30 22:26:29 +09001260 }
1261
Eric Laurentfde16d52012-12-03 14:42:39 -08001262 flags &= ~AudioManager.FLAG_FIXED_VOLUME;
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001263 if ((streamTypeAlias == AudioSystem.STREAM_MUSIC) &&
Eric Laurentfde16d52012-12-03 14:42:39 -08001264 ((device & mFixedVolumeDevices) != 0)) {
1265 flags |= AudioManager.FLAG_FIXED_VOLUME;
1266
1267 // volume is either 0 or max allowed for fixed volume devices
1268 if (index != 0) {
1269 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE &&
1270 (device & mSafeMediaVolumeDevices) != 0) {
1271 index = mSafeMediaVolumeIndex;
1272 } else {
1273 index = streamState.getMaxIndex();
1274 }
1275 }
1276 }
1277
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001278 if (!checkSafeMediaVolume(streamTypeAlias, index, device)) {
John Spurlock3346a802014-05-20 16:25:37 -04001279 mVolumeController.postDisplaySafeVolumeWarning(flags);
Eric Laurentfde16d52012-12-03 14:42:39 -08001280 mPendingVolumeCommand = new StreamVolumeCommand(
1281 streamType, index, flags, device);
1282 } else {
1283 onSetStreamVolume(streamType, index, flags, device);
Eric Laurent42b041e2013-03-29 11:36:03 -07001284 index = mStreamStates[streamType].getIndex(device);
Eric Laurentfde16d52012-12-03 14:42:39 -08001285 }
1286 }
Eric Laurent25101b02011-02-02 09:33:30 -08001287 sendVolumeUpdate(streamType, oldIndex, index, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
1289
Eric Laurent45c90ce2012-04-24 18:44:22 -07001290 /** @see AudioManager#forceVolumeControlStream(int) */
1291 public void forceVolumeControlStream(int streamType, IBinder cb) {
1292 synchronized(mForceControlStreamLock) {
1293 mVolumeControlStream = streamType;
1294 if (mVolumeControlStream == -1) {
1295 if (mForceControlStreamClient != null) {
1296 mForceControlStreamClient.release();
1297 mForceControlStreamClient = null;
1298 }
1299 } else {
1300 mForceControlStreamClient = new ForceControlStreamClient(cb);
1301 }
1302 }
1303 }
1304
1305 private class ForceControlStreamClient implements IBinder.DeathRecipient {
1306 private IBinder mCb; // To be notified of client's death
1307
1308 ForceControlStreamClient(IBinder cb) {
1309 if (cb != null) {
1310 try {
1311 cb.linkToDeath(this, 0);
1312 } catch (RemoteException e) {
1313 // Client has died!
1314 Log.w(TAG, "ForceControlStreamClient() could not link to "+cb+" binder death");
1315 cb = null;
1316 }
1317 }
1318 mCb = cb;
1319 }
1320
1321 public void binderDied() {
1322 synchronized(mForceControlStreamLock) {
1323 Log.w(TAG, "SCO client died");
1324 if (mForceControlStreamClient != this) {
1325 Log.w(TAG, "unregistered control stream client died");
1326 } else {
1327 mForceControlStreamClient = null;
1328 mVolumeControlStream = -1;
1329 }
1330 }
1331 }
1332
1333 public void release() {
1334 if (mCb != null) {
1335 mCb.unlinkToDeath(this, 0);
1336 mCb = null;
1337 }
1338 }
1339 }
1340
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001341 private void sendBroadcastToAll(Intent intent) {
Christopher Tate267603f2015-01-20 14:21:21 -08001342 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
John Spurlock86490862015-02-25 11:22:52 -05001343 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001344 final long ident = Binder.clearCallingIdentity();
1345 try {
1346 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1347 } finally {
1348 Binder.restoreCallingIdentity(ident);
1349 }
1350 }
1351
1352 private void sendStickyBroadcastToAll(Intent intent) {
John Spurlock86490862015-02-25 11:22:52 -05001353 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001354 final long ident = Binder.clearCallingIdentity();
1355 try {
1356 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1357 } finally {
1358 Binder.restoreCallingIdentity(ident);
1359 }
1360 }
1361
Eric Laurent25101b02011-02-02 09:33:30 -08001362 // UI update and Broadcast Intent
1363 private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) {
Eric Laurent212532b2014-07-21 15:43:18 -07001364 if (!isPlatformVoice() && (streamType == AudioSystem.STREAM_RING)) {
Eric Laurent25101b02011-02-02 09:33:30 -08001365 streamType = AudioSystem.STREAM_NOTIFICATION;
1366 }
1367
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001368 if (streamType == AudioSystem.STREAM_MUSIC) {
1369 flags = updateFlagsForSystemAudio(flags);
Jungshik Jang1a6be6e2014-09-16 11:04:54 +09001370 }
John Spurlock3346a802014-05-20 16:25:37 -04001371 mVolumeController.postVolumeChanged(streamType, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001374 // If Hdmi-CEC system audio mode is on, we show volume bar only when TV
1375 // receives volume notification from Audio Receiver.
1376 private int updateFlagsForSystemAudio(int flags) {
1377 if (mHdmiTvClient != null) {
1378 synchronized (mHdmiTvClient) {
1379 if (mHdmiSystemAudioSupported &&
1380 ((flags & AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME) == 0)) {
1381 flags &= ~AudioManager.FLAG_SHOW_UI;
1382 }
1383 }
1384 }
1385 return flags;
1386 }
1387
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001388 // UI update and Broadcast Intent
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001389 private void sendMasterMuteUpdate(boolean muted, int flags) {
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001390 mVolumeController.postMasterMuteChanged(updateFlagsForSystemAudio(flags));
Justin Koh57978ed2012-04-03 17:37:58 -07001391 broadcastMasterMuteStatus(muted);
1392 }
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001393
Justin Koh57978ed2012-04-03 17:37:58 -07001394 private void broadcastMasterMuteStatus(boolean muted) {
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001395 Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
1396 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, muted);
Justin Koh57978ed2012-04-03 17:37:58 -07001397 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1398 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001399 sendStickyBroadcastToAll(intent);
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001400 }
1401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 * Sets the stream state's index, and posts a message to set system volume.
1404 * This will not call out to the UI. Assumes a valid stream type.
1405 *
1406 * @param streamType Type of the stream
1407 * @param index Desired volume index of the stream
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001408 * @param device the device whose volume must be changed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 * @param force If true, set the volume even if the desired volume is same
1410 * as the current volume.
1411 */
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001412 private void setStreamVolumeInt(int streamType,
1413 int index,
1414 int device,
Eric Laurent42b041e2013-03-29 11:36:03 -07001415 boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurent5b4e6542010-03-19 20:02:21 -07001417
Eric Laurent42b041e2013-03-29 11:36:03 -07001418 if (streamState.setIndex(index, device) || force) {
1419 // Post message to set system volume (it in turn will post a message
1420 // to persist).
1421 sendMsg(mAudioHandler,
1422 MSG_SET_DEVICE_VOLUME,
1423 SENDMSG_QUEUE,
1424 device,
1425 0,
1426 streamState,
1427 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 }
1430
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001431 private void setSystemAudioMute(boolean state) {
1432 if (mHdmiManager == null || mHdmiTvClient == null) return;
1433 synchronized (mHdmiManager) {
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001434 if (!mHdmiSystemAudioSupported) return;
1435 synchronized (mHdmiTvClient) {
1436 final long token = Binder.clearCallingIdentity();
1437 try {
1438 mHdmiTvClient.setSystemAudioMute(state);
1439 } finally {
1440 Binder.restoreCallingIdentity(token);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001441 }
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001442 }
1443 }
1444 }
1445
Eric Laurent25101b02011-02-02 09:33:30 -08001446 /** get stream mute state. */
1447 public boolean isStreamMute(int streamType) {
RoboErik7c82ced2014-12-04 17:39:08 -08001448 if (streamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1449 streamType = getActiveStreamType(streamType);
1450 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001451 synchronized (VolumeStreamState.class) {
RoboErik4197cb62015-01-21 15:45:32 -08001452 return mStreamStates[streamType].mIsMuted;
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001453 }
Eric Laurent25101b02011-02-02 09:33:30 -08001454 }
1455
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07001456 private class RmtSbmxFullVolDeathHandler implements IBinder.DeathRecipient {
1457 private IBinder mICallback; // To be notified of client's death
1458
1459 RmtSbmxFullVolDeathHandler(IBinder cb) {
1460 mICallback = cb;
1461 try {
1462 cb.linkToDeath(this, 0/*flags*/);
1463 } catch (RemoteException e) {
1464 Log.e(TAG, "can't link to death", e);
1465 }
1466 }
1467
1468 boolean isHandlerFor(IBinder cb) {
1469 return mICallback.equals(cb);
1470 }
1471
1472 void forget() {
1473 try {
1474 mICallback.unlinkToDeath(this, 0/*flags*/);
1475 } catch (NoSuchElementException e) {
1476 Log.e(TAG, "error unlinking to death", e);
1477 }
1478 }
1479
1480 public void binderDied() {
1481 Log.w(TAG, "Recorder with remote submix at full volume died " + mICallback);
1482 forceRemoteSubmixFullVolume(false, mICallback);
1483 }
1484 }
1485
1486 /**
1487 * call must be synchronized on mRmtSbmxFullVolDeathHandlers
1488 * @return true if there is a registered death handler, false otherwise */
1489 private boolean discardRmtSbmxFullVolDeathHandlerFor(IBinder cb) {
1490 Iterator<RmtSbmxFullVolDeathHandler> it = mRmtSbmxFullVolDeathHandlers.iterator();
1491 while (it.hasNext()) {
1492 final RmtSbmxFullVolDeathHandler handler = it.next();
1493 if (handler.isHandlerFor(cb)) {
1494 handler.forget();
1495 mRmtSbmxFullVolDeathHandlers.remove(handler);
1496 return true;
1497 }
1498 }
1499 return false;
1500 }
1501
1502 /** call synchronized on mRmtSbmxFullVolDeathHandlers */
1503 private boolean hasRmtSbmxFullVolDeathHandlerFor(IBinder cb) {
1504 Iterator<RmtSbmxFullVolDeathHandler> it = mRmtSbmxFullVolDeathHandlers.iterator();
1505 while (it.hasNext()) {
1506 if (it.next().isHandlerFor(cb)) {
1507 return true;
1508 }
1509 }
1510 return false;
1511 }
1512
1513 private int mRmtSbmxFullVolRefCount = 0;
1514 private ArrayList<RmtSbmxFullVolDeathHandler> mRmtSbmxFullVolDeathHandlers =
1515 new ArrayList<RmtSbmxFullVolDeathHandler>();
1516
1517 public void forceRemoteSubmixFullVolume(boolean startForcing, IBinder cb) {
1518 if (cb == null) {
1519 return;
1520 }
1521 if ((PackageManager.PERMISSION_GRANTED != mContext.checkCallingOrSelfPermission(
1522 android.Manifest.permission.CAPTURE_AUDIO_OUTPUT))) {
1523 Log.w(TAG, "Trying to call forceRemoteSubmixFullVolume() without CAPTURE_AUDIO_OUTPUT");
1524 return;
1525 }
1526 synchronized(mRmtSbmxFullVolDeathHandlers) {
1527 boolean applyRequired = false;
1528 if (startForcing) {
1529 if (!hasRmtSbmxFullVolDeathHandlerFor(cb)) {
1530 mRmtSbmxFullVolDeathHandlers.add(new RmtSbmxFullVolDeathHandler(cb));
1531 if (mRmtSbmxFullVolRefCount == 0) {
1532 mFullVolumeDevices |= AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1533 mFixedVolumeDevices |= AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1534 applyRequired = true;
1535 }
1536 mRmtSbmxFullVolRefCount++;
1537 }
1538 } else {
1539 if (discardRmtSbmxFullVolDeathHandlerFor(cb) && (mRmtSbmxFullVolRefCount > 0)) {
1540 mRmtSbmxFullVolRefCount--;
1541 if (mRmtSbmxFullVolRefCount == 0) {
1542 mFullVolumeDevices &= ~AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1543 mFixedVolumeDevices &= ~AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1544 applyRequired = true;
1545 }
1546 }
1547 }
1548 if (applyRequired) {
1549 // Assumes only STREAM_MUSIC going through DEVICE_OUT_REMOTE_SUBMIX
1550 checkAllFixedVolumeDevices(AudioSystem.STREAM_MUSIC);
1551 mStreamStates[AudioSystem.STREAM_MUSIC].applyAllVolumes();
1552 }
1553 }
1554 }
1555
John Spurlockee5ad722015-03-03 16:17:21 -05001556 private void setMasterMuteInternal(boolean mute, int flags, String callingPackage, int uid) {
RoboErik7c82ced2014-12-04 17:39:08 -08001557 if (mAppOps.noteOp(AppOpsManager.OP_AUDIO_MASTER_VOLUME, uid, callingPackage)
1558 != AppOpsManager.MODE_ALLOWED) {
Julia Reynolds4a21b252014-06-04 11:11:43 -04001559 return;
1560 }
John Spurlockee5ad722015-03-03 16:17:21 -05001561 if (mute != AudioSystem.getMasterMute()) {
1562 setSystemAudioMute(mute);
1563 AudioSystem.setMasterMute(mute);
Justin Koh57978ed2012-04-03 17:37:58 -07001564 // Post a persist master volume msg
John Spurlockee5ad722015-03-03 16:17:21 -05001565 sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME_MUTE, SENDMSG_REPLACE, mute ? 1
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001566 : 0, UserHandle.getCallingUserId(), null, PERSIST_DELAY);
John Spurlockee5ad722015-03-03 16:17:21 -05001567 sendMasterMuteUpdate(mute, flags);
RoboErik7c82ced2014-12-04 17:39:08 -08001568
1569 Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
John Spurlockee5ad722015-03-03 16:17:21 -05001570 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, mute);
RoboErik7c82ced2014-12-04 17:39:08 -08001571 sendBroadcastToAll(intent);
Jason Simmons1ce5b262012-02-02 13:00:17 -08001572 }
Mike Lockwoodce952c82011-11-14 10:47:42 -08001573 }
1574
1575 /** get master mute state. */
1576 public boolean isMasterMute() {
Mike Lockwood3194ea92011-12-07 11:47:31 -08001577 return AudioSystem.getMasterMute();
Mike Lockwoodce952c82011-11-14 10:47:42 -08001578 }
1579
John Spurlockee5ad722015-03-03 16:17:21 -05001580 public void setMasterMute(boolean mute, int flags, String callingPackage) {
1581 setMasterMuteInternal(mute, flags, callingPackage, Binder.getCallingUid());
1582 }
1583
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07001584 protected static int getMaxStreamVolume(int streamType) {
1585 return MAX_STREAM_VOLUME[streamType];
1586 }
1587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 /** @see AudioManager#getStreamVolume(int) */
1589 public int getStreamVolume(int streamType) {
1590 ensureValidStreamType(streamType);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001591 int device = getDeviceForStream(streamType);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001592 synchronized (VolumeStreamState.class) {
1593 int index = mStreamStates[streamType].getIndex(device);
Eric Laurent4bbcc652012-09-24 14:26:30 -07001594
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001595 // by convention getStreamVolume() returns 0 when a stream is muted.
RoboErik4197cb62015-01-21 15:45:32 -08001596 if (mStreamStates[streamType].mIsMuted) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001597 index = 0;
1598 }
1599 if (index != 0 && (mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) &&
1600 (device & mFixedVolumeDevices) != 0) {
1601 index = mStreamStates[streamType].getMaxIndex();
1602 }
1603 return (index + 5) / 10;
Eric Laurent42b041e2013-03-29 11:36:03 -07001604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
1607 /** @see AudioManager#getStreamMaxVolume(int) */
1608 public int getStreamMaxVolume(int streamType) {
1609 ensureValidStreamType(streamType);
Eric Laurenta553c252009-07-17 12:17:14 -07001610 return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
Eric Laurent25101b02011-02-02 09:33:30 -08001613 /** Get last audible volume before stream was muted. */
1614 public int getLastAudibleStreamVolume(int streamType) {
1615 ensureValidStreamType(streamType);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001616 int device = getDeviceForStream(streamType);
Eric Laurent42b041e2013-03-29 11:36:03 -07001617 return (mStreamStates[streamType].getIndex(device) + 5) / 10;
Eric Laurent25101b02011-02-02 09:33:30 -08001618 }
1619
John Spurlockee5ad722015-03-03 16:17:21 -05001620 /** @see AudioManager#getUiSoundsStreamType() */
1621 public int getUiSoundsStreamType() {
John Spurlock4f0f1202014-08-05 13:28:33 -04001622 return mStreamVolumeAlias[AudioSystem.STREAM_SYSTEM];
Eric Laurent6d517662012-04-23 18:42:39 -07001623 }
1624
Emily Bernier22c921a2014-05-28 11:01:32 -04001625 /** @see AudioManager#setMicrophoneMute(boolean) */
1626 public void setMicrophoneMute(boolean on, String callingPackage) {
1627 if (mAppOps.noteOp(AppOpsManager.OP_MUTE_MICROPHONE, Binder.getCallingUid(),
1628 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1629 return;
1630 }
Jean-Michel Trivi4a4fea02014-08-29 18:14:09 -07001631 if (!checkAudioSettingsPermission("setMicrophoneMute()")) {
1632 return;
1633 }
Emily Bernier22c921a2014-05-28 11:01:32 -04001634
1635 AudioSystem.muteMicrophone(on);
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001636 // Post a persist microphone msg.
1637 sendMsg(mAudioHandler, MSG_PERSIST_MICROPHONE_MUTE, SENDMSG_REPLACE, on ? 1
1638 : 0, UserHandle.getCallingUserId(), null, PERSIST_DELAY);
Emily Bernier22c921a2014-05-28 11:01:32 -04001639 }
1640
John Spurlock661f2cf2014-11-17 10:29:10 -05001641 @Override
1642 public int getRingerModeExternal() {
1643 synchronized(mSettingsLock) {
1644 return mRingerModeExternal;
1645 }
1646 }
1647
1648 @Override
1649 public int getRingerModeInternal() {
Glenn Kastenba195eb2011-12-13 09:30:40 -08001650 synchronized(mSettingsLock) {
1651 return mRingerMode;
1652 }
1653 }
1654
1655 private void ensureValidRingerMode(int ringerMode) {
John Spurlock97559372014-10-24 16:27:36 -04001656 if (!isValidRingerMode(ringerMode)) {
Glenn Kastenba195eb2011-12-13 09:30:40 -08001657 throw new IllegalArgumentException("Bad ringer mode " + ringerMode);
1658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660
John Spurlock97559372014-10-24 16:27:36 -04001661 /** @see AudioManager#isValidRingerMode(int) */
1662 public boolean isValidRingerMode(int ringerMode) {
1663 return ringerMode >= 0 && ringerMode <= AudioManager.RINGER_MODE_MAX;
1664 }
1665
John Spurlock661f2cf2014-11-17 10:29:10 -05001666 public void setRingerModeExternal(int ringerMode, String caller) {
John Spurlockaf88a192014-12-23 16:14:44 -05001667 setRingerMode(ringerMode, caller, true /*external*/);
John Spurlock661f2cf2014-11-17 10:29:10 -05001668 }
1669
1670 public void setRingerModeInternal(int ringerMode, String caller) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05001671 enforceVolumeController("setRingerModeInternal");
John Spurlockaf88a192014-12-23 16:14:44 -05001672 setRingerMode(ringerMode, caller, false /*external*/);
John Spurlock661f2cf2014-11-17 10:29:10 -05001673 }
1674
1675 private void setRingerMode(int ringerMode, String caller, boolean external) {
Eric Laurent212532b2014-07-21 15:43:18 -07001676 if (mUseFixedVolume || isPlatformTelevision()) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001677 return;
1678 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001679 if (caller == null || caller.length() == 0) {
1680 throw new IllegalArgumentException("Bad caller: " + caller);
1681 }
John Spurlock97559372014-10-24 16:27:36 -04001682 ensureValidRingerMode(ringerMode);
Eric Laurent24482012012-05-10 09:41:17 -07001683 if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) {
1684 ringerMode = AudioManager.RINGER_MODE_SILENT;
1685 }
John Spurlockaf88a192014-12-23 16:14:44 -05001686 final long identity = Binder.clearCallingIdentity();
1687 try {
1688 synchronized (mSettingsLock) {
1689 final int ringerModeInternal = getRingerModeInternal();
1690 final int ringerModeExternal = getRingerModeExternal();
1691 if (external) {
1692 setRingerModeExt(ringerMode);
1693 if (mRingerModeDelegate != null) {
1694 ringerMode = mRingerModeDelegate.onSetRingerModeExternal(ringerModeExternal,
1695 ringerMode, caller, ringerModeInternal);
1696 }
1697 if (ringerMode != ringerModeInternal) {
1698 setRingerModeInt(ringerMode, true /*persist*/);
1699 }
1700 } else /*internal*/ {
1701 if (ringerMode != ringerModeInternal) {
1702 setRingerModeInt(ringerMode, true /*persist*/);
1703 }
1704 if (mRingerModeDelegate != null) {
1705 ringerMode = mRingerModeDelegate.onSetRingerModeInternal(ringerModeInternal,
1706 ringerMode, caller, ringerModeExternal);
1707 }
1708 setRingerModeExt(ringerMode);
John Spurlock57627792014-12-11 11:29:54 -05001709 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001710 }
John Spurlockaf88a192014-12-23 16:14:44 -05001711 } finally {
1712 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 }
1714 }
1715
John Spurlock661f2cf2014-11-17 10:29:10 -05001716 private void setRingerModeExt(int ringerMode) {
1717 synchronized(mSettingsLock) {
1718 if (ringerMode == mRingerModeExternal) return;
1719 mRingerModeExternal = ringerMode;
John Spurlocke5b42d92014-10-15 12:03:48 -04001720 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001721 // Send sticky broadcast
John Spurlockbcc10872014-11-28 15:29:21 -05001722 broadcastRingerMode(AudioManager.RINGER_MODE_CHANGED_ACTION, ringerMode);
John Spurlocke5b42d92014-10-15 12:03:48 -04001723 }
1724
Eric Laurent4050c932009-07-08 02:52:14 -07001725 private void setRingerModeInt(int ringerMode, boolean persist) {
John Spurlockbcc10872014-11-28 15:29:21 -05001726 final boolean change;
Glenn Kastenba195eb2011-12-13 09:30:40 -08001727 synchronized(mSettingsLock) {
John Spurlockbcc10872014-11-28 15:29:21 -05001728 change = mRingerMode != ringerMode;
Glenn Kastenba195eb2011-12-13 09:30:40 -08001729 mRingerMode = ringerMode;
1730 }
Jason Parekhb1096152009-03-24 17:48:25 -07001731
Eric Laurent5b4e6542010-03-19 20:02:21 -07001732 // Mute stream if not previously muted by ringer mode and ringer mode
1733 // is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
1734 // Unmute stream if previously muted by ringer mode and ringer mode
1735 // is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
Jason Parekhb1096152009-03-24 17:48:25 -07001736 int numStreamTypes = AudioSystem.getNumStreamTypes();
John Spurlock661f2cf2014-11-17 10:29:10 -05001737 final boolean ringerModeMute = ringerMode == AudioManager.RINGER_MODE_VIBRATE
1738 || ringerMode == AudioManager.RINGER_MODE_SILENT;
Eric Laurent5b4e6542010-03-19 20:02:21 -07001739 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
John Spurlock661f2cf2014-11-17 10:29:10 -05001740 final boolean isMuted = isStreamMutedByRingerMode(streamType);
1741 final boolean shouldMute = ringerModeMute && isStreamAffectedByRingerMode(streamType);
1742 if (isMuted == shouldMute) continue;
1743 if (!shouldMute) {
1744 // unmute
1745 // ring and notifications volume should never be 0 when not silenced
1746 // on voice capable devices or devices that support vibration
1747 if ((isPlatformVoice() || mHasVibrator) &&
1748 mStreamVolumeAlias[streamType] == AudioSystem.STREAM_RING) {
1749 synchronized (VolumeStreamState.class) {
John Spurlock2bb02ec2015-03-02 13:13:06 -05001750 SparseIntArray indexMap = mStreamStates[streamType].mIndexMap;
1751 for (int i = 0; i < indexMap.size(); i++) {
1752 int device = indexMap.keyAt(i);
1753 int value = indexMap.valueAt(i);
1754 if (value == 0) {
1755 indexMap.put(device, 10);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001756 }
1757 }
Eric Laurent9e0d25f2015-02-12 17:28:53 -08001758 // Persist volume for stream ring when it is changed here
1759 final int device = getDeviceForStream(streamType);
1760 sendMsg(mAudioHandler,
1761 MSG_PERSIST_VOLUME,
1762 SENDMSG_QUEUE,
1763 device,
1764 0,
1765 mStreamStates[streamType],
1766 PERSIST_DELAY);
Eric Laurentb024c302011-10-14 17:19:27 -07001767 }
Eric Laurent9bcf4012009-06-12 06:09:28 -07001768 }
RoboErik4197cb62015-01-21 15:45:32 -08001769 mStreamStates[streamType].mute(false);
John Spurlock661f2cf2014-11-17 10:29:10 -05001770 mRingerModeMutedStreams &= ~(1 << streamType);
Eric Laurent5b4e6542010-03-19 20:02:21 -07001771 } else {
John Spurlock661f2cf2014-11-17 10:29:10 -05001772 // mute
RoboErik4197cb62015-01-21 15:45:32 -08001773 mStreamStates[streamType].mute(true);
John Spurlock661f2cf2014-11-17 10:29:10 -05001774 mRingerModeMutedStreams |= (1 << streamType);
Jason Parekhb1096152009-03-24 17:48:25 -07001775 }
1776 }
Eric Laurenta553c252009-07-17 12:17:14 -07001777
Jason Parekhb1096152009-03-24 17:48:25 -07001778 // Post a persist ringer mode msg
Eric Laurent4050c932009-07-08 02:52:14 -07001779 if (persist) {
Eric Laurentafbb0472011-12-15 09:04:23 -08001780 sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE,
Eric Laurent4050c932009-07-08 02:52:14 -07001781 SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
1782 }
John Spurlockbcc10872014-11-28 15:29:21 -05001783 if (change) {
1784 // Send sticky broadcast
1785 broadcastRingerMode(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION, ringerMode);
1786 }
Jason Parekhb1096152009-03-24 17:48:25 -07001787 }
1788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 /** @see AudioManager#shouldVibrate(int) */
1790 public boolean shouldVibrate(int vibrateType) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07001791 if (!mHasVibrator) return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792
1793 switch (getVibrateSetting(vibrateType)) {
1794
1795 case AudioManager.VIBRATE_SETTING_ON:
John Spurlock57627792014-12-11 11:29:54 -05001796 return getRingerModeExternal() != AudioManager.RINGER_MODE_SILENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797
1798 case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
John Spurlock57627792014-12-11 11:29:54 -05001799 return getRingerModeExternal() == AudioManager.RINGER_MODE_VIBRATE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800
1801 case AudioManager.VIBRATE_SETTING_OFF:
Daniel Sandlerbcac4962010-04-12 13:23:57 -04001802 // return false, even for incoming calls
1803 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804
1805 default:
1806 return false;
1807 }
1808 }
1809
1810 /** @see AudioManager#getVibrateSetting(int) */
1811 public int getVibrateSetting(int vibrateType) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07001812 if (!mHasVibrator) return AudioManager.VIBRATE_SETTING_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 return (mVibrateSetting >> (vibrateType * 2)) & 3;
1814 }
1815
1816 /** @see AudioManager#setVibrateSetting(int, int) */
1817 public void setVibrateSetting(int vibrateType, int vibrateSetting) {
1818
Eric Laurentbffc3d12012-05-07 17:43:49 -07001819 if (!mHasVibrator) return;
1820
John Spurlock61560172015-02-06 19:46:04 -05001821 mVibrateSetting = AudioSystem.getValueForVibrateSetting(mVibrateSetting, vibrateType,
1822 vibrateSetting);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823
1824 // Broadcast change
1825 broadcastVibrateSetting(vibrateType);
1826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
1828
Eric Laurent9272b4b2010-01-23 17:12:59 -08001829 private class SetModeDeathHandler implements IBinder.DeathRecipient {
1830 private IBinder mCb; // To be notified of client's death
Marco Nelissenf1ddd512011-08-10 14:15:44 -07001831 private int mPid;
Eric Laurent9272b4b2010-01-23 17:12:59 -08001832 private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
1833
Eric Laurent9f103de2011-09-08 15:04:23 -07001834 SetModeDeathHandler(IBinder cb, int pid) {
Eric Laurent9272b4b2010-01-23 17:12:59 -08001835 mCb = cb;
Eric Laurent9f103de2011-09-08 15:04:23 -07001836 mPid = pid;
Eric Laurent9272b4b2010-01-23 17:12:59 -08001837 }
1838
1839 public void binderDied() {
Eric Laurentd7454be2011-09-14 08:45:58 -07001840 int newModeOwnerPid = 0;
Eric Laurent9272b4b2010-01-23 17:12:59 -08001841 synchronized(mSetModeDeathHandlers) {
1842 Log.w(TAG, "setMode() client died");
1843 int index = mSetModeDeathHandlers.indexOf(this);
1844 if (index < 0) {
1845 Log.w(TAG, "unregistered setMode() client died");
1846 } else {
Eric Laurentd7454be2011-09-14 08:45:58 -07001847 newModeOwnerPid = setModeInt(AudioSystem.MODE_NORMAL, mCb, mPid);
Eric Laurent9272b4b2010-01-23 17:12:59 -08001848 }
1849 }
Eric Laurent9f103de2011-09-08 15:04:23 -07001850 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
1851 // SCO connections not started by the application changing the mode
Eric Laurentd7454be2011-09-14 08:45:58 -07001852 if (newModeOwnerPid != 0) {
Eric Laurent6b5e22d2013-03-28 16:10:45 -07001853 final long ident = Binder.clearCallingIdentity();
1854 disconnectBluetoothSco(newModeOwnerPid);
1855 Binder.restoreCallingIdentity(ident);
Eric Laurent9f103de2011-09-08 15:04:23 -07001856 }
Eric Laurent9272b4b2010-01-23 17:12:59 -08001857 }
1858
Marco Nelissenf1ddd512011-08-10 14:15:44 -07001859 public int getPid() {
1860 return mPid;
1861 }
1862
Eric Laurent9272b4b2010-01-23 17:12:59 -08001863 public void setMode(int mode) {
1864 mMode = mode;
1865 }
1866
1867 public int getMode() {
1868 return mMode;
1869 }
1870
1871 public IBinder getBinder() {
1872 return mCb;
1873 }
1874 }
1875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 /** @see AudioManager#setMode(int) */
Eric Laurent9272b4b2010-01-23 17:12:59 -08001877 public void setMode(int mode, IBinder cb) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07001878 if (DEBUG_MODE) { Log.v(TAG, "setMode(mode=" + mode + ")"); }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 if (!checkAudioSettingsPermission("setMode()")) {
1880 return;
1881 }
Eric Laurenta553c252009-07-17 12:17:14 -07001882
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07001883 if ( (mode == AudioSystem.MODE_IN_CALL) &&
1884 (mContext.checkCallingOrSelfPermission(
1885 android.Manifest.permission.MODIFY_PHONE_STATE)
1886 != PackageManager.PERMISSION_GRANTED)) {
1887 Log.w(TAG, "MODIFY_PHONE_STATE Permission Denial: setMode(MODE_IN_CALL) from pid="
1888 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1889 return;
1890 }
1891
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001892 if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) {
Eric Laurenta553c252009-07-17 12:17:14 -07001893 return;
1894 }
1895
Eric Laurentd7454be2011-09-14 08:45:58 -07001896 int newModeOwnerPid = 0;
Eric Laurent9f103de2011-09-08 15:04:23 -07001897 synchronized(mSetModeDeathHandlers) {
Eric Laurenta553c252009-07-17 12:17:14 -07001898 if (mode == AudioSystem.MODE_CURRENT) {
1899 mode = mMode;
1900 }
Eric Laurentd7454be2011-09-14 08:45:58 -07001901 newModeOwnerPid = setModeInt(mode, cb, Binder.getCallingPid());
Eric Laurent9f103de2011-09-08 15:04:23 -07001902 }
1903 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
1904 // SCO connections not started by the application changing the mode
Eric Laurentd7454be2011-09-14 08:45:58 -07001905 if (newModeOwnerPid != 0) {
1906 disconnectBluetoothSco(newModeOwnerPid);
Eric Laurent9f103de2011-09-08 15:04:23 -07001907 }
1908 }
Jean-Michel Trivi2ade5762010-12-11 13:18:30 -08001909
Eric Laurent9f103de2011-09-08 15:04:23 -07001910 // must be called synchronized on mSetModeDeathHandlers
Eric Laurentd7454be2011-09-14 08:45:58 -07001911 // setModeInt() returns a valid PID if the audio mode was successfully set to
Eric Laurent9f103de2011-09-08 15:04:23 -07001912 // any mode other than NORMAL.
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07001913 private int setModeInt(int mode, IBinder cb, int pid) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07001914 if (DEBUG_MODE) { Log.v(TAG, "setModeInt(mode=" + mode + ", pid=" + pid + ")"); }
Eric Laurentd7454be2011-09-14 08:45:58 -07001915 int newModeOwnerPid = 0;
Eric Laurent9f103de2011-09-08 15:04:23 -07001916 if (cb == null) {
1917 Log.e(TAG, "setModeInt() called with null binder");
Eric Laurentd7454be2011-09-14 08:45:58 -07001918 return newModeOwnerPid;
Eric Laurent9f103de2011-09-08 15:04:23 -07001919 }
Jean-Michel Trivi2ade5762010-12-11 13:18:30 -08001920
Eric Laurent9f103de2011-09-08 15:04:23 -07001921 SetModeDeathHandler hdlr = null;
1922 Iterator iter = mSetModeDeathHandlers.iterator();
1923 while (iter.hasNext()) {
1924 SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
1925 if (h.getPid() == pid) {
1926 hdlr = h;
1927 // Remove from client list so that it is re-inserted at top of list
1928 iter.remove();
1929 hdlr.getBinder().unlinkToDeath(hdlr, 0);
1930 break;
1931 }
1932 }
1933 int status = AudioSystem.AUDIO_STATUS_OK;
1934 do {
1935 if (mode == AudioSystem.MODE_NORMAL) {
1936 // get new mode from client at top the list if any
1937 if (!mSetModeDeathHandlers.isEmpty()) {
1938 hdlr = mSetModeDeathHandlers.get(0);
1939 cb = hdlr.getBinder();
1940 mode = hdlr.getMode();
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07001941 if (DEBUG_MODE) {
1942 Log.w(TAG, " using mode=" + mode + " instead due to death hdlr at pid="
1943 + hdlr.mPid);
1944 }
Eric Laurentb9c9d262009-05-06 08:13:20 -07001945 }
Eric Laurent9f103de2011-09-08 15:04:23 -07001946 } else {
1947 if (hdlr == null) {
1948 hdlr = new SetModeDeathHandler(cb, pid);
1949 }
1950 // Register for client death notification
1951 try {
1952 cb.linkToDeath(hdlr, 0);
1953 } catch (RemoteException e) {
1954 // Client has died!
1955 Log.w(TAG, "setMode() could not link to "+cb+" binder death");
1956 }
1957
1958 // Last client to call setMode() is always at top of client list
1959 // as required by SetModeDeathHandler.binderDied()
1960 mSetModeDeathHandlers.add(0, hdlr);
1961 hdlr.setMode(mode);
1962 }
1963
1964 if (mode != mMode) {
1965 status = AudioSystem.setPhoneState(mode);
1966 if (status == AudioSystem.AUDIO_STATUS_OK) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07001967 if (DEBUG_MODE) { Log.v(TAG, " mode successfully set to " + mode); }
Eric Laurent9f103de2011-09-08 15:04:23 -07001968 mMode = mode;
1969 } else {
1970 if (hdlr != null) {
1971 mSetModeDeathHandlers.remove(hdlr);
1972 cb.unlinkToDeath(hdlr, 0);
1973 }
1974 // force reading new top of mSetModeDeathHandlers stack
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07001975 if (DEBUG_MODE) { Log.w(TAG, " mode set to MODE_NORMAL after phoneState pb"); }
Eric Laurent9f103de2011-09-08 15:04:23 -07001976 mode = AudioSystem.MODE_NORMAL;
1977 }
1978 } else {
1979 status = AudioSystem.AUDIO_STATUS_OK;
1980 }
1981 } while (status != AudioSystem.AUDIO_STATUS_OK && !mSetModeDeathHandlers.isEmpty());
1982
1983 if (status == AudioSystem.AUDIO_STATUS_OK) {
1984 if (mode != AudioSystem.MODE_NORMAL) {
Eric Laurentd7454be2011-09-14 08:45:58 -07001985 if (mSetModeDeathHandlers.isEmpty()) {
1986 Log.e(TAG, "setMode() different from MODE_NORMAL with empty mode client stack");
1987 } else {
1988 newModeOwnerPid = mSetModeDeathHandlers.get(0).getPid();
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
1991 int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001992 int device = getDeviceForStream(streamType);
Eric Laurent42b041e2013-03-29 11:36:03 -07001993 int index = mStreamStates[mStreamVolumeAlias[streamType]].getIndex(device);
1994 setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, true);
Eric Laurent6d517662012-04-23 18:42:39 -07001995
1996 updateStreamVolumeAlias(true /*updateVolumes*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
Eric Laurentd7454be2011-09-14 08:45:58 -07001998 return newModeOwnerPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
2000
2001 /** @see AudioManager#getMode() */
2002 public int getMode() {
2003 return mMode;
2004 }
2005
Eric Laurente78fced2013-03-15 16:03:47 -07002006 //==========================================================================================
2007 // Sound Effects
2008 //==========================================================================================
2009
2010 private static final String TAG_AUDIO_ASSETS = "audio_assets";
2011 private static final String ATTR_VERSION = "version";
2012 private static final String TAG_GROUP = "group";
2013 private static final String ATTR_GROUP_NAME = "name";
2014 private static final String TAG_ASSET = "asset";
2015 private static final String ATTR_ASSET_ID = "id";
2016 private static final String ATTR_ASSET_FILE = "file";
2017
2018 private static final String ASSET_FILE_VERSION = "1.0";
2019 private static final String GROUP_TOUCH_SOUNDS = "touch_sounds";
2020
Glenn Kasten167d1a22013-07-23 16:24:41 -07002021 private static final int SOUND_EFFECTS_LOAD_TIMEOUT_MS = 5000;
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002022
2023 class LoadSoundEffectReply {
2024 public int mStatus = 1;
2025 };
2026
Eric Laurente78fced2013-03-15 16:03:47 -07002027 private void loadTouchSoundAssetDefaults() {
2028 SOUND_EFFECT_FILES.add("Effect_Tick.ogg");
2029 for (int i = 0; i < AudioManager.NUM_SOUND_EFFECTS; i++) {
2030 SOUND_EFFECT_FILES_MAP[i][0] = 0;
2031 SOUND_EFFECT_FILES_MAP[i][1] = -1;
2032 }
2033 }
2034
2035 private void loadTouchSoundAssets() {
2036 XmlResourceParser parser = null;
2037
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002038 // only load assets once.
2039 if (!SOUND_EFFECT_FILES.isEmpty()) {
2040 return;
2041 }
2042
Eric Laurente78fced2013-03-15 16:03:47 -07002043 loadTouchSoundAssetDefaults();
2044
2045 try {
2046 parser = mContext.getResources().getXml(com.android.internal.R.xml.audio_assets);
2047
2048 XmlUtils.beginDocument(parser, TAG_AUDIO_ASSETS);
2049 String version = parser.getAttributeValue(null, ATTR_VERSION);
2050 boolean inTouchSoundsGroup = false;
2051
2052 if (ASSET_FILE_VERSION.equals(version)) {
2053 while (true) {
2054 XmlUtils.nextElement(parser);
2055 String element = parser.getName();
2056 if (element == null) {
2057 break;
2058 }
2059 if (element.equals(TAG_GROUP)) {
2060 String name = parser.getAttributeValue(null, ATTR_GROUP_NAME);
2061 if (GROUP_TOUCH_SOUNDS.equals(name)) {
2062 inTouchSoundsGroup = true;
2063 break;
2064 }
2065 }
2066 }
2067 while (inTouchSoundsGroup) {
2068 XmlUtils.nextElement(parser);
2069 String element = parser.getName();
2070 if (element == null) {
2071 break;
2072 }
2073 if (element.equals(TAG_ASSET)) {
2074 String id = parser.getAttributeValue(null, ATTR_ASSET_ID);
2075 String file = parser.getAttributeValue(null, ATTR_ASSET_FILE);
2076 int fx;
2077
2078 try {
2079 Field field = AudioManager.class.getField(id);
2080 fx = field.getInt(null);
2081 } catch (Exception e) {
2082 Log.w(TAG, "Invalid touch sound ID: "+id);
2083 continue;
2084 }
2085
2086 int i = SOUND_EFFECT_FILES.indexOf(file);
2087 if (i == -1) {
2088 i = SOUND_EFFECT_FILES.size();
2089 SOUND_EFFECT_FILES.add(file);
2090 }
2091 SOUND_EFFECT_FILES_MAP[fx][0] = i;
2092 } else {
2093 break;
2094 }
2095 }
2096 }
2097 } catch (Resources.NotFoundException e) {
2098 Log.w(TAG, "audio assets file not found", e);
2099 } catch (XmlPullParserException e) {
2100 Log.w(TAG, "XML parser exception reading touch sound assets", e);
2101 } catch (IOException e) {
2102 Log.w(TAG, "I/O exception reading touch sound assets", e);
2103 } finally {
2104 if (parser != null) {
2105 parser.close();
2106 }
2107 }
2108 }
2109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 /** @see AudioManager#playSoundEffect(int) */
2111 public void playSoundEffect(int effectType) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002112 playSoundEffectVolume(effectType, -1.0f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114
2115 /** @see AudioManager#playSoundEffect(int, float) */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 public void playSoundEffectVolume(int effectType, float volume) {
Natalie Silvanovich559c76d2014-05-01 10:16:24 -07002117 if (effectType >= AudioManager.NUM_SOUND_EFFECTS || effectType < 0) {
2118 Log.w(TAG, "AudioService effectType value " + effectType + " out of range");
2119 return;
2120 }
2121
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002122 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_QUEUE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 effectType, (int) (volume * 1000), null, 0);
2124 }
2125
2126 /**
2127 * Loads samples into the soundpool.
Glenn Kasten5c17a822011-11-30 09:41:01 -08002128 * This method must be called at first when sound effects are enabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 */
2130 public boolean loadSoundEffects() {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002131 int attempts = 3;
2132 LoadSoundEffectReply reply = new LoadSoundEffectReply();
Eric Laurenta60e2122010-12-28 16:49:07 -08002133
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002134 synchronized (reply) {
2135 sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, reply, 0);
2136 while ((reply.mStatus == 1) && (attempts-- > 0)) {
Eric Laurent117b7bb2011-01-16 17:07:27 -08002137 try {
Glenn Kasten167d1a22013-07-23 16:24:41 -07002138 reply.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002139 } catch (InterruptedException e) {
2140 Log.w(TAG, "loadSoundEffects Interrupted while waiting sound pool loaded.");
Eric Laurent117b7bb2011-01-16 17:07:27 -08002141 }
Eric Laurenta60e2122010-12-28 16:49:07 -08002142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 }
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002144 return (reply.mStatus == 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 }
2146
2147 /**
2148 * Unloads samples from the sound pool.
2149 * This method can be called to free some memory when
2150 * sound effects are disabled.
2151 */
2152 public void unloadSoundEffects() {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002153 sendMsg(mAudioHandler, MSG_UNLOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155
Eric Laurenta60e2122010-12-28 16:49:07 -08002156 class SoundPoolListenerThread extends Thread {
2157 public SoundPoolListenerThread() {
2158 super("SoundPoolListenerThread");
2159 }
2160
2161 @Override
2162 public void run() {
2163
2164 Looper.prepare();
2165 mSoundPoolLooper = Looper.myLooper();
2166
2167 synchronized (mSoundEffectsLock) {
2168 if (mSoundPool != null) {
2169 mSoundPoolCallBack = new SoundPoolCallback();
2170 mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack);
2171 }
2172 mSoundEffectsLock.notify();
2173 }
2174 Looper.loop();
2175 }
2176 }
2177
2178 private final class SoundPoolCallback implements
2179 android.media.SoundPool.OnLoadCompleteListener {
2180
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002181 int mStatus = 1; // 1 means neither error nor last sample loaded yet
2182 List<Integer> mSamples = new ArrayList<Integer>();
Eric Laurenta60e2122010-12-28 16:49:07 -08002183
2184 public int status() {
2185 return mStatus;
2186 }
2187
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002188 public void setSamples(int[] samples) {
2189 for (int i = 0; i < samples.length; i++) {
2190 // do not wait ack for samples rejected upfront by SoundPool
2191 if (samples[i] > 0) {
2192 mSamples.add(samples[i]);
2193 }
2194 }
Eric Laurenta60e2122010-12-28 16:49:07 -08002195 }
2196
2197 public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
2198 synchronized (mSoundEffectsLock) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002199 int i = mSamples.indexOf(sampleId);
2200 if (i >= 0) {
2201 mSamples.remove(i);
Eric Laurenta60e2122010-12-28 16:49:07 -08002202 }
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002203 if ((status != 0) || mSamples. isEmpty()) {
2204 mStatus = status;
Eric Laurenta60e2122010-12-28 16:49:07 -08002205 mSoundEffectsLock.notify();
2206 }
2207 }
2208 }
2209 }
2210
Eric Laurent4050c932009-07-08 02:52:14 -07002211 /** @see AudioManager#reloadAudioSettings() */
2212 public void reloadAudioSettings() {
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07002213 readAudioSettings(false /*userSwitch*/);
2214 }
2215
2216 private void readAudioSettings(boolean userSwitch) {
Eric Laurent4050c932009-07-08 02:52:14 -07002217 // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
2218 readPersistedSettings();
2219
2220 // restore volume settings
2221 int numStreamTypes = AudioSystem.getNumStreamTypes();
2222 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
2223 VolumeStreamState streamState = mStreamStates[streamType];
2224
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07002225 if (userSwitch && mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) {
2226 continue;
2227 }
2228
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07002229 streamState.readSettings();
2230 synchronized (VolumeStreamState.class) {
Eric Laurent3172d5e2012-05-09 11:38:16 -07002231 // unmute stream that was muted but is not affect by mute anymore
RoboErik4197cb62015-01-21 15:45:32 -08002232 if (streamState.mIsMuted && ((!isStreamAffectedByMute(streamType) &&
Eric Laurent83a017b2013-03-19 18:15:31 -07002233 !isStreamMutedByRingerMode(streamType)) || mUseFixedVolume)) {
RoboErik4197cb62015-01-21 15:45:32 -08002234 streamState.mIsMuted = false;
Eric Laurent4050c932009-07-08 02:52:14 -07002235 }
Eric Laurent4050c932009-07-08 02:52:14 -07002236 }
2237 }
2238
Eric Laurent33902db2012-10-07 16:15:07 -07002239 // apply new ringer mode before checking volume for alias streams so that streams
2240 // muted by ringer mode have the correct volume
John Spurlock661f2cf2014-11-17 10:29:10 -05002241 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent33902db2012-10-07 16:15:07 -07002242
Eric Laurent212532b2014-07-21 15:43:18 -07002243 checkAllFixedVolumeDevices();
Eric Laurent24482012012-05-10 09:41:17 -07002244 checkAllAliasStreamVolumes();
2245
Eric Laurentd640bd32012-09-28 18:01:48 -07002246 synchronized (mSafeMediaVolumeState) {
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002247 mMusicActiveMs = MathUtils.constrain(Settings.Secure.getIntForUser(mContentResolver,
2248 Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, 0, UserHandle.USER_CURRENT),
2249 0, UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX);
Eric Laurentd640bd32012-09-28 18:01:48 -07002250 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) {
Eric Laurentf1a457d2012-09-20 16:27:23 -07002251 enforceSafeMediaVolume();
2252 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07002253 }
Eric Laurent4050c932009-07-08 02:52:14 -07002254 }
2255
Dianne Hackborn961cae92013-03-20 14:59:43 -07002256 /** @see AudioManager#setSpeakerphoneOn(boolean) */
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002257 public void setSpeakerphoneOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -07002258 if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
2259 return;
2260 }
Johan Gustavsson7337bee2013-03-01 15:53:30 +01002261
2262 if (on) {
2263 if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
2264 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
2265 AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE, null, 0);
2266 }
2267 mForcedUseForComm = AudioSystem.FORCE_SPEAKER;
2268 } else if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER){
2269 mForcedUseForComm = AudioSystem.FORCE_NONE;
2270 }
Eric Laurentfa640152011-03-12 15:59:51 -08002271
Eric Laurentafbb0472011-12-15 09:04:23 -08002272 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002273 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002274 }
2275
2276 /** @see AudioManager#isSpeakerphoneOn() */
2277 public boolean isSpeakerphoneOn() {
Eric Laurentfa640152011-03-12 15:59:51 -08002278 return (mForcedUseForComm == AudioSystem.FORCE_SPEAKER);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002279 }
2280
Dianne Hackborn961cae92013-03-20 14:59:43 -07002281 /** @see AudioManager#setBluetoothScoOn(boolean) */
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002282 public void setBluetoothScoOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -07002283 if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
2284 return;
2285 }
Johan Gustavsson7337bee2013-03-01 15:53:30 +01002286
2287 if (on) {
2288 mForcedUseForComm = AudioSystem.FORCE_BT_SCO;
2289 } else if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
2290 mForcedUseForComm = AudioSystem.FORCE_NONE;
2291 }
Eric Laurentfa640152011-03-12 15:59:51 -08002292
Eric Laurentafbb0472011-12-15 09:04:23 -08002293 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002294 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
Eric Laurentafbb0472011-12-15 09:04:23 -08002295 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002296 AudioSystem.FOR_RECORD, mForcedUseForComm, null, 0);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002297 }
2298
2299 /** @see AudioManager#isBluetoothScoOn() */
2300 public boolean isBluetoothScoOn() {
Eric Laurentfa640152011-03-12 15:59:51 -08002301 return (mForcedUseForComm == AudioSystem.FORCE_BT_SCO);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002302 }
2303
Dianne Hackborn961cae92013-03-20 14:59:43 -07002304 /** @see AudioManager#setBluetoothA2dpOn(boolean) */
Eric Laurent78472112012-05-21 08:57:21 -07002305 public void setBluetoothA2dpOn(boolean on) {
Eric Laurentc390bed2012-07-03 12:24:05 -07002306 synchronized (mBluetoothA2dpEnabledLock) {
2307 mBluetoothA2dpEnabled = on;
2308 sendMsg(mAudioHandler, MSG_SET_FORCE_BT_A2DP_USE, SENDMSG_QUEUE,
2309 AudioSystem.FOR_MEDIA,
2310 mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP,
2311 null, 0);
2312 }
Eric Laurent78472112012-05-21 08:57:21 -07002313 }
2314
2315 /** @see AudioManager#isBluetoothA2dpOn() */
2316 public boolean isBluetoothA2dpOn() {
2317 synchronized (mBluetoothA2dpEnabledLock) {
2318 return mBluetoothA2dpEnabled;
2319 }
2320 }
2321
Eric Laurent3def1ee2010-03-17 23:26:26 -07002322 /** @see AudioManager#startBluetoothSco() */
Eric Laurent83900752014-05-15 15:14:22 -07002323 public void startBluetoothSco(IBinder cb, int targetSdkVersion) {
2324 int scoAudioMode =
2325 (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR2) ?
Liejun Taof4e51d82014-07-16 11:18:29 -07002326 SCO_MODE_VIRTUAL_CALL : SCO_MODE_UNDEFINED;
Eric Laurent83900752014-05-15 15:14:22 -07002327 startBluetoothScoInt(cb, scoAudioMode);
2328 }
2329
2330 /** @see AudioManager#startBluetoothScoVirtualCall() */
2331 public void startBluetoothScoVirtualCall(IBinder cb) {
2332 startBluetoothScoInt(cb, SCO_MODE_VIRTUAL_CALL);
2333 }
2334
2335 void startBluetoothScoInt(IBinder cb, int scoAudioMode){
Eric Laurentdc03c612011-04-01 10:59:41 -07002336 if (!checkAudioSettingsPermission("startBluetoothSco()") ||
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002337 !mSystemReady) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002338 return;
2339 }
Eric Laurent854938a2011-02-22 12:05:20 -08002340 ScoClient client = getScoClient(cb, true);
Eric Laurentf5a1fc32013-03-11 18:52:57 -07002341 // The calling identity must be cleared before calling ScoClient.incCount().
2342 // inCount() calls requestScoState() which in turn can call BluetoothHeadset APIs
2343 // and this must be done on behalf of system server to make sure permissions are granted.
2344 // The caller identity must be cleared after getScoClient() because it is needed if a new
2345 // client is created.
2346 final long ident = Binder.clearCallingIdentity();
Eric Laurent83900752014-05-15 15:14:22 -07002347 client.incCount(scoAudioMode);
Eric Laurent2a57ca92013-03-07 17:29:27 -08002348 Binder.restoreCallingIdentity(ident);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002349 }
2350
2351 /** @see AudioManager#stopBluetoothSco() */
2352 public void stopBluetoothSco(IBinder cb){
Eric Laurentdc03c612011-04-01 10:59:41 -07002353 if (!checkAudioSettingsPermission("stopBluetoothSco()") ||
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002354 !mSystemReady) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002355 return;
2356 }
Eric Laurent854938a2011-02-22 12:05:20 -08002357 ScoClient client = getScoClient(cb, false);
Eric Laurentf5a1fc32013-03-11 18:52:57 -07002358 // The calling identity must be cleared before calling ScoClient.decCount().
2359 // decCount() calls requestScoState() which in turn can call BluetoothHeadset APIs
2360 // and this must be done on behalf of system server to make sure permissions are granted.
2361 final long ident = Binder.clearCallingIdentity();
Eric Laurent854938a2011-02-22 12:05:20 -08002362 if (client != null) {
2363 client.decCount();
2364 }
Eric Laurent2a57ca92013-03-07 17:29:27 -08002365 Binder.restoreCallingIdentity(ident);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002366 }
2367
Eric Laurent78472112012-05-21 08:57:21 -07002368
Eric Laurent3def1ee2010-03-17 23:26:26 -07002369 private class ScoClient implements IBinder.DeathRecipient {
2370 private IBinder mCb; // To be notified of client's death
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002371 private int mCreatorPid;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002372 private int mStartcount; // number of SCO connections started by this client
2373
2374 ScoClient(IBinder cb) {
2375 mCb = cb;
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002376 mCreatorPid = Binder.getCallingPid();
Eric Laurent3def1ee2010-03-17 23:26:26 -07002377 mStartcount = 0;
2378 }
2379
2380 public void binderDied() {
2381 synchronized(mScoClients) {
2382 Log.w(TAG, "SCO client died");
2383 int index = mScoClients.indexOf(this);
2384 if (index < 0) {
2385 Log.w(TAG, "unregistered SCO client died");
2386 } else {
2387 clearCount(true);
2388 mScoClients.remove(this);
2389 }
2390 }
2391 }
2392
Eric Laurent83900752014-05-15 15:14:22 -07002393 public void incCount(int scoAudioMode) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002394 synchronized(mScoClients) {
Eric Laurent83900752014-05-15 15:14:22 -07002395 requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED, scoAudioMode);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002396 if (mStartcount == 0) {
2397 try {
2398 mCb.linkToDeath(this, 0);
2399 } catch (RemoteException e) {
2400 // client has already died!
2401 Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death");
2402 }
2403 }
2404 mStartcount++;
2405 }
2406 }
2407
2408 public void decCount() {
2409 synchronized(mScoClients) {
2410 if (mStartcount == 0) {
2411 Log.w(TAG, "ScoClient.decCount() already 0");
2412 } else {
2413 mStartcount--;
2414 if (mStartcount == 0) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07002415 try {
2416 mCb.unlinkToDeath(this, 0);
2417 } catch (NoSuchElementException e) {
2418 Log.w(TAG, "decCount() going to 0 but not registered to binder");
2419 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002420 }
Eric Laurentc18c9132013-04-12 17:24:56 -07002421 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, 0);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002422 }
2423 }
2424 }
2425
2426 public void clearCount(boolean stopSco) {
2427 synchronized(mScoClients) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07002428 if (mStartcount != 0) {
2429 try {
2430 mCb.unlinkToDeath(this, 0);
2431 } catch (NoSuchElementException e) {
2432 Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
2433 }
2434 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002435 mStartcount = 0;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002436 if (stopSco) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002437 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, 0);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002438 }
2439 }
2440 }
2441
2442 public int getCount() {
2443 return mStartcount;
2444 }
2445
2446 public IBinder getBinder() {
2447 return mCb;
2448 }
2449
Eric Laurentd7454be2011-09-14 08:45:58 -07002450 public int getPid() {
2451 return mCreatorPid;
2452 }
2453
Eric Laurent3def1ee2010-03-17 23:26:26 -07002454 public int totalCount() {
2455 synchronized(mScoClients) {
2456 int count = 0;
2457 int size = mScoClients.size();
2458 for (int i = 0; i < size; i++) {
2459 count += mScoClients.get(i).getCount();
2460 }
2461 return count;
2462 }
2463 }
2464
Eric Laurent83900752014-05-15 15:14:22 -07002465 private void requestScoState(int state, int scoAudioMode) {
Eric Laurent62ef7672010-11-24 10:58:32 -08002466 checkScoAudioState();
Eric Laurentdc03c612011-04-01 10:59:41 -07002467 if (totalCount() == 0) {
2468 if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
2469 // Make sure that the state transitions to CONNECTING even if we cannot initiate
2470 // the connection.
2471 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
2472 // Accept SCO audio activation only in NORMAL audio mode or if the mode is
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002473 // currently controlled by the same client process.
Eric Laurent9f103de2011-09-08 15:04:23 -07002474 synchronized(mSetModeDeathHandlers) {
2475 if ((mSetModeDeathHandlers.isEmpty() ||
2476 mSetModeDeathHandlers.get(0).getPid() == mCreatorPid) &&
2477 (mScoAudioState == SCO_STATE_INACTIVE ||
2478 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
2479 if (mScoAudioState == SCO_STATE_INACTIVE) {
Eric Laurent83900752014-05-15 15:14:22 -07002480 mScoAudioMode = scoAudioMode;
Liejun Taof4e51d82014-07-16 11:18:29 -07002481 if (scoAudioMode == SCO_MODE_UNDEFINED) {
Andre Eisenbach570cc532014-10-28 17:03:18 -07002482 if (mBluetoothHeadsetDevice != null) {
2483 mScoAudioMode = new Integer(Settings.Global.getInt(
2484 mContentResolver,
2485 "bluetooth_sco_channel_"+
2486 mBluetoothHeadsetDevice.getAddress(),
2487 SCO_MODE_VIRTUAL_CALL));
2488 if (mScoAudioMode > SCO_MODE_MAX || mScoAudioMode < 0) {
2489 mScoAudioMode = SCO_MODE_VIRTUAL_CALL;
2490 }
2491 } else {
2492 mScoAudioMode = SCO_MODE_RAW;
Liejun Taof4e51d82014-07-16 11:18:29 -07002493 }
2494 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002495 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
Liejun Taof4e51d82014-07-16 11:18:29 -07002496 boolean status = false;
Eric Laurentc18c9132013-04-12 17:24:56 -07002497 if (mScoAudioMode == SCO_MODE_RAW) {
2498 status = mBluetoothHeadset.connectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002499 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002500 status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
2501 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002502 } else if (mScoAudioMode == SCO_MODE_VR) {
2503 status = mBluetoothHeadset.startVoiceRecognition(
2504 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002505 }
Liejun Taof4e51d82014-07-16 11:18:29 -07002506
Eric Laurentc18c9132013-04-12 17:24:56 -07002507 if (status) {
Eric Laurent9f103de2011-09-08 15:04:23 -07002508 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
2509 } else {
2510 broadcastScoConnectionState(
2511 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2512 }
2513 } else if (getBluetoothHeadset()) {
2514 mScoAudioState = SCO_STATE_ACTIVATE_REQ;
Eric Laurentdc03c612011-04-01 10:59:41 -07002515 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002516 } else {
2517 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
2518 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED);
Eric Laurentdc03c612011-04-01 10:59:41 -07002519 }
2520 } else {
Eric Laurent9f103de2011-09-08 15:04:23 -07002521 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
Eric Laurentdc03c612011-04-01 10:59:41 -07002522 }
Eric Laurentdc03c612011-04-01 10:59:41 -07002523 }
Eric Laurent62ef7672010-11-24 10:58:32 -08002524 } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED &&
Eric Laurentdc03c612011-04-01 10:59:41 -07002525 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
2526 mScoAudioState == SCO_STATE_ACTIVATE_REQ)) {
2527 if (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) {
Marco Nelissen671db6f2011-09-06 16:29:12 -07002528 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
Liejun Taof4e51d82014-07-16 11:18:29 -07002529 boolean status = false;
Eric Laurentc18c9132013-04-12 17:24:56 -07002530 if (mScoAudioMode == SCO_MODE_RAW) {
2531 status = mBluetoothHeadset.disconnectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002532 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002533 status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
2534 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002535 } else if (mScoAudioMode == SCO_MODE_VR) {
2536 status = mBluetoothHeadset.stopVoiceRecognition(
2537 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002538 }
Liejun Taof4e51d82014-07-16 11:18:29 -07002539
Eric Laurentc18c9132013-04-12 17:24:56 -07002540 if (!status) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002541 mScoAudioState = SCO_STATE_INACTIVE;
2542 broadcastScoConnectionState(
2543 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2544 }
2545 } else if (getBluetoothHeadset()) {
2546 mScoAudioState = SCO_STATE_DEACTIVATE_REQ;
2547 }
2548 } else {
2549 mScoAudioState = SCO_STATE_INACTIVE;
2550 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2551 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002552 }
2553 }
2554 }
2555 }
2556
Eric Laurent62ef7672010-11-24 10:58:32 -08002557 private void checkScoAudioState() {
2558 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null &&
Eric Laurentdc03c612011-04-01 10:59:41 -07002559 mScoAudioState == SCO_STATE_INACTIVE &&
Eric Laurent62ef7672010-11-24 10:58:32 -08002560 mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice)
2561 != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
2562 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2563 }
2564 }
2565
Eric Laurent854938a2011-02-22 12:05:20 -08002566 private ScoClient getScoClient(IBinder cb, boolean create) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002567 synchronized(mScoClients) {
Eric Laurent854938a2011-02-22 12:05:20 -08002568 ScoClient client = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002569 int size = mScoClients.size();
2570 for (int i = 0; i < size; i++) {
2571 client = mScoClients.get(i);
2572 if (client.getBinder() == cb)
2573 return client;
2574 }
Eric Laurent854938a2011-02-22 12:05:20 -08002575 if (create) {
2576 client = new ScoClient(cb);
2577 mScoClients.add(client);
2578 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002579 return client;
2580 }
2581 }
2582
Eric Laurentd7454be2011-09-14 08:45:58 -07002583 public void clearAllScoClients(int exceptPid, boolean stopSco) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002584 synchronized(mScoClients) {
Eric Laurent854938a2011-02-22 12:05:20 -08002585 ScoClient savedClient = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002586 int size = mScoClients.size();
2587 for (int i = 0; i < size; i++) {
Eric Laurent854938a2011-02-22 12:05:20 -08002588 ScoClient cl = mScoClients.get(i);
Eric Laurentd7454be2011-09-14 08:45:58 -07002589 if (cl.getPid() != exceptPid) {
Eric Laurent854938a2011-02-22 12:05:20 -08002590 cl.clearCount(stopSco);
2591 } else {
2592 savedClient = cl;
2593 }
2594 }
2595 mScoClients.clear();
2596 if (savedClient != null) {
2597 mScoClients.add(savedClient);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002598 }
2599 }
2600 }
2601
Eric Laurentdc03c612011-04-01 10:59:41 -07002602 private boolean getBluetoothHeadset() {
2603 boolean result = false;
2604 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
2605 if (adapter != null) {
2606 result = adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
2607 BluetoothProfile.HEADSET);
2608 }
2609 // If we could not get a bluetooth headset proxy, send a failure message
2610 // without delay to reset the SCO audio state and clear SCO clients.
2611 // If we could get a proxy, send a delayed failure message that will reset our state
2612 // in case we don't receive onServiceConnected().
Eric Laurentafbb0472011-12-15 09:04:23 -08002613 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurentdc03c612011-04-01 10:59:41 -07002614 SENDMSG_REPLACE, 0, 0, null, result ? BT_HEADSET_CNCT_TIMEOUT_MS : 0);
2615 return result;
2616 }
2617
Eric Laurentd7454be2011-09-14 08:45:58 -07002618 private void disconnectBluetoothSco(int exceptPid) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002619 synchronized(mScoClients) {
2620 checkScoAudioState();
2621 if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL ||
2622 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
2623 if (mBluetoothHeadsetDevice != null) {
2624 if (mBluetoothHeadset != null) {
2625 if (!mBluetoothHeadset.stopVoiceRecognition(
Eric Laurentb06ac832011-05-25 15:55:18 -07002626 mBluetoothHeadsetDevice)) {
Eric Laurentafbb0472011-12-15 09:04:23 -08002627 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurentdc03c612011-04-01 10:59:41 -07002628 SENDMSG_REPLACE, 0, 0, null, 0);
2629 }
2630 } else if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL &&
2631 getBluetoothHeadset()) {
2632 mScoAudioState = SCO_STATE_DEACTIVATE_EXT_REQ;
2633 }
2634 }
2635 } else {
Eric Laurentd7454be2011-09-14 08:45:58 -07002636 clearAllScoClients(exceptPid, true);
Eric Laurentdc03c612011-04-01 10:59:41 -07002637 }
2638 }
2639 }
2640
2641 private void resetBluetoothSco() {
2642 synchronized(mScoClients) {
Eric Laurentd7454be2011-09-14 08:45:58 -07002643 clearAllScoClients(0, false);
Eric Laurentdc03c612011-04-01 10:59:41 -07002644 mScoAudioState = SCO_STATE_INACTIVE;
2645 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2646 }
2647 }
2648
2649 private void broadcastScoConnectionState(int state) {
Eric Laurent2a57ca92013-03-07 17:29:27 -08002650 sendMsg(mAudioHandler, MSG_BROADCAST_BT_CONNECTION_STATE,
2651 SENDMSG_QUEUE, state, 0, null, 0);
2652 }
2653
2654 private void onBroadcastScoConnectionState(int state) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002655 if (state != mScoConnectionState) {
2656 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
2657 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
2658 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE,
2659 mScoConnectionState);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002660 sendStickyBroadcastToAll(newIntent);
Eric Laurentdc03c612011-04-01 10:59:41 -07002661 mScoConnectionState = state;
2662 }
2663 }
2664
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07002665 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
2666 new BluetoothProfile.ServiceListener() {
2667 public void onServiceConnected(int profile, BluetoothProfile proxy) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002668 BluetoothDevice btDevice;
2669 List<BluetoothDevice> deviceList;
2670 switch(profile) {
2671 case BluetoothProfile.A2DP:
seunghwan.hong4fe77952014-10-29 17:43:20 +09002672 synchronized (mConnectedDevices) {
2673 synchronized (mA2dpAvrcpLock) {
2674 mA2dp = (BluetoothA2dp) proxy;
2675 deviceList = mA2dp.getConnectedDevices();
2676 if (deviceList.size() > 0) {
2677 btDevice = deviceList.get(0);
John Du5a0cf7a2013-07-19 11:30:34 -07002678 int state = mA2dp.getConnectionState(btDevice);
2679 int delay = checkSendBecomingNoisyIntent(
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002680 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2681 (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
John Du5a0cf7a2013-07-19 11:30:34 -07002682 queueMsgUnderWakeLock(mAudioHandler,
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002683 MSG_SET_A2DP_SINK_CONNECTION_STATE,
John Du5a0cf7a2013-07-19 11:30:34 -07002684 state,
2685 0,
2686 btDevice,
2687 delay);
2688 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07002689 }
Eric Laurent62ef7672010-11-24 10:58:32 -08002690 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002691 break;
2692
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002693 case BluetoothProfile.A2DP_SINK:
2694 deviceList = proxy.getConnectedDevices();
2695 if (deviceList.size() > 0) {
2696 btDevice = deviceList.get(0);
2697 synchronized (mConnectedDevices) {
2698 int state = proxy.getConnectionState(btDevice);
2699 queueMsgUnderWakeLock(mAudioHandler,
2700 MSG_SET_A2DP_SRC_CONNECTION_STATE,
2701 state,
2702 0,
2703 btDevice,
2704 0 /* delay */);
2705 }
2706 }
2707 break;
2708
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002709 case BluetoothProfile.HEADSET:
2710 synchronized (mScoClients) {
2711 // Discard timeout message
2712 mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED);
2713 mBluetoothHeadset = (BluetoothHeadset) proxy;
2714 deviceList = mBluetoothHeadset.getConnectedDevices();
2715 if (deviceList.size() > 0) {
2716 mBluetoothHeadsetDevice = deviceList.get(0);
2717 } else {
2718 mBluetoothHeadsetDevice = null;
2719 }
2720 // Refresh SCO audio state
2721 checkScoAudioState();
2722 // Continue pending action if any
2723 if (mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
2724 mScoAudioState == SCO_STATE_DEACTIVATE_REQ ||
2725 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
2726 boolean status = false;
2727 if (mBluetoothHeadsetDevice != null) {
2728 switch (mScoAudioState) {
2729 case SCO_STATE_ACTIVATE_REQ:
2730 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
Eric Laurentc18c9132013-04-12 17:24:56 -07002731 if (mScoAudioMode == SCO_MODE_RAW) {
2732 status = mBluetoothHeadset.connectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002733 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002734 status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
2735 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002736 } else if (mScoAudioMode == SCO_MODE_VR) {
2737 status = mBluetoothHeadset.startVoiceRecognition(
2738 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002739 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002740 break;
2741 case SCO_STATE_DEACTIVATE_REQ:
Eric Laurentc18c9132013-04-12 17:24:56 -07002742 if (mScoAudioMode == SCO_MODE_RAW) {
2743 status = mBluetoothHeadset.disconnectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002744 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002745 status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
2746 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002747 } else if (mScoAudioMode == SCO_MODE_VR) {
2748 status = mBluetoothHeadset.stopVoiceRecognition(
2749 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002750 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002751 break;
2752 case SCO_STATE_DEACTIVATE_EXT_REQ:
2753 status = mBluetoothHeadset.stopVoiceRecognition(
2754 mBluetoothHeadsetDevice);
2755 }
2756 }
2757 if (!status) {
Eric Laurentafbb0472011-12-15 09:04:23 -08002758 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002759 SENDMSG_REPLACE, 0, 0, null, 0);
Eric Laurentdc03c612011-04-01 10:59:41 -07002760 }
2761 }
Eric Laurentdc03c612011-04-01 10:59:41 -07002762 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002763 break;
2764
2765 default:
2766 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002767 }
2768 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07002769 public void onServiceDisconnected(int profile) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002770 switch(profile) {
2771 case BluetoothProfile.A2DP:
seunghwan.hong4fe77952014-10-29 17:43:20 +09002772 synchronized (mConnectedDevices) {
2773 synchronized (mA2dpAvrcpLock) {
2774 mA2dp = null;
John Du5a0cf7a2013-07-19 11:30:34 -07002775 if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) {
2776 makeA2dpDeviceUnavailableNow(
2777 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP));
2778 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002779 }
2780 }
2781 break;
2782
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002783 case BluetoothProfile.A2DP_SINK:
2784 synchronized (mConnectedDevices) {
2785 if (mConnectedDevices.containsKey(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP)) {
2786 makeA2dpSrcUnavailable(
2787 mConnectedDevices.get(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP));
2788 }
2789 }
2790 break;
2791
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002792 case BluetoothProfile.HEADSET:
2793 synchronized (mScoClients) {
2794 mBluetoothHeadset = null;
2795 }
2796 break;
2797
2798 default:
2799 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002800 }
2801 }
2802 };
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002803
Eric Laurentc34dcc12012-09-10 13:51:52 -07002804 private void onCheckMusicActive() {
Eric Laurentd640bd32012-09-28 18:01:48 -07002805 synchronized (mSafeMediaVolumeState) {
2806 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07002807 int device = getDeviceForStream(AudioSystem.STREAM_MUSIC);
2808
2809 if ((device & mSafeMediaVolumeDevices) != 0) {
2810 sendMsg(mAudioHandler,
2811 MSG_CHECK_MUSIC_ACTIVE,
2812 SENDMSG_REPLACE,
Eric Laurentf1a457d2012-09-20 16:27:23 -07002813 0,
Eric Laurentc34dcc12012-09-10 13:51:52 -07002814 0,
2815 null,
2816 MUSIC_ACTIVE_POLL_PERIOD_MS);
Eric Laurent42b041e2013-03-29 11:36:03 -07002817 int index = mStreamStates[AudioSystem.STREAM_MUSIC].getIndex(device);
Eric Laurentf1a457d2012-09-20 16:27:23 -07002818 if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0) &&
2819 (index > mSafeMediaVolumeIndex)) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07002820 // Approximate cumulative active music time
2821 mMusicActiveMs += MUSIC_ACTIVE_POLL_PERIOD_MS;
2822 if (mMusicActiveMs > UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX) {
2823 setSafeMediaVolumeEnabled(true);
2824 mMusicActiveMs = 0;
Eric Laurentc34dcc12012-09-10 13:51:52 -07002825 }
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002826 saveMusicActiveMs();
Eric Laurentc34dcc12012-09-10 13:51:52 -07002827 }
2828 }
2829 }
2830 }
2831 }
2832
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002833 private void saveMusicActiveMs() {
2834 mAudioHandler.obtainMessage(MSG_PERSIST_MUSIC_ACTIVE_MS, mMusicActiveMs, 0).sendToTarget();
2835 }
2836
Eric Laurentd640bd32012-09-28 18:01:48 -07002837 private void onConfigureSafeVolume(boolean force) {
2838 synchronized (mSafeMediaVolumeState) {
2839 int mcc = mContext.getResources().getConfiguration().mcc;
2840 if ((mMcc != mcc) || ((mMcc == 0) && force)) {
2841 mSafeMediaVolumeIndex = mContext.getResources().getInteger(
2842 com.android.internal.R.integer.config_safe_media_volume_index) * 10;
John Spurlock35134602014-07-24 18:10:48 -04002843 boolean safeMediaVolumeEnabled =
2844 SystemProperties.getBoolean("audio.safemedia.force", false)
2845 || mContext.getResources().getBoolean(
2846 com.android.internal.R.bool.config_safe_media_volume_enabled);
Eric Laurent05274f32012-11-29 12:48:18 -08002847
2848 // The persisted state is either "disabled" or "active": this is the state applied
2849 // next time we boot and cannot be "inactive"
2850 int persistedState;
Eric Laurentd640bd32012-09-28 18:01:48 -07002851 if (safeMediaVolumeEnabled) {
Eric Laurent05274f32012-11-29 12:48:18 -08002852 persistedState = SAFE_MEDIA_VOLUME_ACTIVE;
2853 // The state can already be "inactive" here if the user has forced it before
2854 // the 30 seconds timeout for forced configuration. In this case we don't reset
2855 // it to "active".
2856 if (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_INACTIVE) {
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002857 if (mMusicActiveMs == 0) {
2858 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE;
2859 enforceSafeMediaVolume();
2860 } else {
2861 // We have existing playback time recorded, already confirmed.
2862 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE;
2863 }
Eric Laurent05274f32012-11-29 12:48:18 -08002864 }
Eric Laurentd640bd32012-09-28 18:01:48 -07002865 } else {
Eric Laurent05274f32012-11-29 12:48:18 -08002866 persistedState = SAFE_MEDIA_VOLUME_DISABLED;
Eric Laurentd640bd32012-09-28 18:01:48 -07002867 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_DISABLED;
2868 }
2869 mMcc = mcc;
Eric Laurent05274f32012-11-29 12:48:18 -08002870 sendMsg(mAudioHandler,
2871 MSG_PERSIST_SAFE_VOLUME_STATE,
2872 SENDMSG_QUEUE,
2873 persistedState,
2874 0,
2875 null,
2876 0);
Eric Laurentd640bd32012-09-28 18:01:48 -07002877 }
2878 }
2879 }
2880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 ///////////////////////////////////////////////////////////////////////////
2882 // Internal methods
2883 ///////////////////////////////////////////////////////////////////////////
2884
2885 /**
2886 * Checks if the adjustment should change ringer mode instead of just
2887 * adjusting volume. If so, this will set the proper ringer mode and volume
2888 * indices on the stream states.
2889 */
RoboErik5452e252015-02-06 15:33:53 -08002890 private int checkForRingerModeChange(int oldIndex, int direction, int step, boolean isMuted) {
John Spurlocka11b4af2014-06-01 11:52:23 -04002891 int result = FLAG_ADJUST_VOLUME;
John Spurlock661f2cf2014-11-17 10:29:10 -05002892 int ringerMode = getRingerModeInternal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
Eric Laurentbffc3d12012-05-07 17:43:49 -07002894 switch (ringerMode) {
2895 case RINGER_MODE_NORMAL:
2896 if (direction == AudioManager.ADJUST_LOWER) {
2897 if (mHasVibrator) {
Eric Laurent24482012012-05-10 09:41:17 -07002898 // "step" is the delta in internal index units corresponding to a
2899 // change of 1 in UI index units.
2900 // Because of rounding when rescaling from one stream index range to its alias
2901 // index range, we cannot simply test oldIndex == step:
2902 // (step <= oldIndex < 2 * step) is equivalent to: (old UI index == 1)
2903 if (step <= oldIndex && oldIndex < 2 * step) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07002904 ringerMode = RINGER_MODE_VIBRATE;
2905 }
2906 } else {
Eric Laurent24482012012-05-10 09:41:17 -07002907 // (oldIndex < step) is equivalent to (old UI index == 0)
John Spurlock86005342014-05-23 11:58:00 -04002908 if ((oldIndex < step)
2909 && VOLUME_SETS_RINGER_MODE_SILENT
2910 && mPrevVolDirection != AudioManager.ADJUST_LOWER) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07002911 ringerMode = RINGER_MODE_SILENT;
2912 }
Eric Laurent3d4c06f2011-08-15 19:58:28 -07002913 }
RoboErik5452e252015-02-06 15:33:53 -08002914 } else if (direction == AudioManager.ADJUST_TOGGLE_MUTE
2915 || direction == AudioManager.ADJUST_MUTE) {
2916 if (mHasVibrator) {
2917 ringerMode = RINGER_MODE_VIBRATE;
2918 } else {
2919 ringerMode = RINGER_MODE_SILENT;
2920 }
2921 // Setting the ringer mode will toggle mute
2922 result &= ~FLAG_ADJUST_VOLUME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07002924 break;
2925 case RINGER_MODE_VIBRATE:
2926 if (!mHasVibrator) {
2927 Log.e(TAG, "checkForRingerModeChange() current ringer mode is vibrate" +
2928 "but no vibrator is present");
2929 break;
2930 }
Amith Yamasanic696a532011-10-28 17:02:37 -07002931 if ((direction == AudioManager.ADJUST_LOWER)) {
RoboErik5452e252015-02-06 15:33:53 -08002932 // This is the case we were muted with the volume turned up
2933 if (oldIndex >= 2 * step && isMuted) {
2934 ringerMode = RINGER_MODE_NORMAL;
2935 } else if (mPrevVolDirection != AudioManager.ADJUST_LOWER) {
John Spurlock795a5142014-12-08 14:09:35 -05002936 if (VOLUME_SETS_RINGER_MODE_SILENT) {
2937 ringerMode = RINGER_MODE_SILENT;
2938 } else {
2939 result |= AudioManager.FLAG_SHOW_VIBRATE_HINT;
2940 }
Amith Yamasanic696a532011-10-28 17:02:37 -07002941 }
RoboErik5452e252015-02-06 15:33:53 -08002942 } else if (direction == AudioManager.ADJUST_RAISE
2943 || direction == AudioManager.ADJUST_TOGGLE_MUTE
2944 || direction == AudioManager.ADJUST_UNMUTE) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07002945 ringerMode = RINGER_MODE_NORMAL;
Amith Yamasanic696a532011-10-28 17:02:37 -07002946 }
John Spurlocka11b4af2014-06-01 11:52:23 -04002947 result &= ~FLAG_ADJUST_VOLUME;
Eric Laurentbffc3d12012-05-07 17:43:49 -07002948 break;
2949 case RINGER_MODE_SILENT:
RoboErik5452e252015-02-06 15:33:53 -08002950 if (direction == AudioManager.ADJUST_LOWER && oldIndex >= 2 * step && isMuted) {
2951 // This is the case we were muted with the volume turned up
2952 ringerMode = RINGER_MODE_NORMAL;
2953 } else if (direction == AudioManager.ADJUST_RAISE
2954 || direction == AudioManager.ADJUST_TOGGLE_MUTE
2955 || direction == AudioManager.ADJUST_UNMUTE) {
John Spurlocka11b4af2014-06-01 11:52:23 -04002956 if (PREVENT_VOLUME_ADJUSTMENT_IF_SILENT) {
2957 result |= AudioManager.FLAG_SHOW_SILENT_HINT;
Eric Laurentbffc3d12012-05-07 17:43:49 -07002958 } else {
RoboErik5452e252015-02-06 15:33:53 -08002959 if (mHasVibrator && direction == AudioManager.ADJUST_RAISE) {
John Spurlocka11b4af2014-06-01 11:52:23 -04002960 ringerMode = RINGER_MODE_VIBRATE;
2961 } else {
RoboErik5452e252015-02-06 15:33:53 -08002962 // If we don't have a vibrator or they were toggling mute
2963 // go straight back to normal.
John Spurlocka11b4af2014-06-01 11:52:23 -04002964 ringerMode = RINGER_MODE_NORMAL;
2965 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07002966 }
Daniel Sandler6329bf72010-02-26 15:17:44 -05002967 }
John Spurlocka11b4af2014-06-01 11:52:23 -04002968 result &= ~FLAG_ADJUST_VOLUME;
Eric Laurentbffc3d12012-05-07 17:43:49 -07002969 break;
2970 default:
2971 Log.e(TAG, "checkForRingerModeChange() wrong ringer mode: "+ringerMode);
2972 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 }
2974
John Spurlock661f2cf2014-11-17 10:29:10 -05002975 setRingerMode(ringerMode, TAG + ".checkForRingerModeChange", false /*external*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976
Eric Laurent25101b02011-02-02 09:33:30 -08002977 mPrevVolDirection = direction;
2978
John Spurlocka11b4af2014-06-01 11:52:23 -04002979 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 }
2981
John Spurlock3346a802014-05-20 16:25:37 -04002982 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 public boolean isStreamAffectedByRingerMode(int streamType) {
Eric Laurent9bcf4012009-06-12 06:09:28 -07002984 return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 }
2986
Eric Laurent5b4e6542010-03-19 20:02:21 -07002987 private boolean isStreamMutedByRingerMode(int streamType) {
2988 return (mRingerModeMutedStreams & (1 << streamType)) != 0;
2989 }
2990
Eric Laurent24e0d9b2013-10-03 18:15:07 -07002991 boolean updateRingerModeAffectedStreams() {
2992 int ringerModeAffectedStreams;
2993 // make sure settings for ringer mode are consistent with device type: non voice capable
2994 // devices (tablets) include media stream in silent mode whereas phones don't.
2995 ringerModeAffectedStreams = Settings.System.getIntForUser(mContentResolver,
2996 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
2997 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
2998 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)),
2999 UserHandle.USER_CURRENT);
3000
3001 // ringtone, notification and system streams are always affected by ringer mode
3002 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_RING)|
3003 (1 << AudioSystem.STREAM_NOTIFICATION)|
3004 (1 << AudioSystem.STREAM_SYSTEM);
3005
Eric Laurent212532b2014-07-21 15:43:18 -07003006 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -05003007 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -07003008 ringerModeAffectedStreams = 0;
3009 break;
3010 default:
John Spurlock77e54d92014-08-11 12:16:24 -04003011 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
Eric Laurent212532b2014-07-21 15:43:18 -07003012 break;
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003013 }
Eric Laurent212532b2014-07-21 15:43:18 -07003014
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003015 synchronized (mCameraSoundForced) {
3016 if (mCameraSoundForced) {
3017 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
3018 } else {
3019 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
3020 }
3021 }
3022 if (mStreamVolumeAlias[AudioSystem.STREAM_DTMF] == AudioSystem.STREAM_RING) {
3023 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_DTMF);
3024 } else {
3025 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_DTMF);
3026 }
3027
3028 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
3029 Settings.System.putIntForUser(mContentResolver,
3030 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
3031 ringerModeAffectedStreams,
3032 UserHandle.USER_CURRENT);
3033 mRingerModeAffectedStreams = ringerModeAffectedStreams;
3034 return true;
3035 }
3036 return false;
3037 }
3038
John Spurlocka9dfbe8b2015-02-17 11:01:51 -05003039 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 public boolean isStreamAffectedByMute(int streamType) {
3041 return (mMuteAffectedStreams & (1 << streamType)) != 0;
3042 }
3043
3044 private void ensureValidDirection(int direction) {
RoboErik4197cb62015-01-21 15:45:32 -08003045 switch (direction) {
3046 case AudioManager.ADJUST_LOWER:
3047 case AudioManager.ADJUST_RAISE:
3048 case AudioManager.ADJUST_SAME:
3049 case AudioManager.ADJUST_MUTE:
3050 case AudioManager.ADJUST_UNMUTE:
3051 case AudioManager.ADJUST_TOGGLE_MUTE:
3052 break;
3053 default:
3054 throw new IllegalArgumentException("Bad direction " + direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 }
3056 }
3057
Lei Zhang6c798972012-03-02 11:40:12 -08003058 private void ensureValidSteps(int steps) {
3059 if (Math.abs(steps) > MAX_BATCH_VOLUME_ADJUST_STEPS) {
3060 throw new IllegalArgumentException("Bad volume adjust steps " + steps);
3061 }
3062 }
3063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 private void ensureValidStreamType(int streamType) {
3065 if (streamType < 0 || streamType >= mStreamStates.length) {
3066 throw new IllegalArgumentException("Bad stream type " + streamType);
3067 }
3068 }
3069
RoboErik4197cb62015-01-21 15:45:32 -08003070 private boolean isMuteAdjust(int adjust) {
3071 return adjust == AudioManager.ADJUST_MUTE || adjust == AudioManager.ADJUST_UNMUTE
3072 || adjust == AudioManager.ADJUST_TOGGLE_MUTE;
3073 }
3074
Eric Laurent6d517662012-04-23 18:42:39 -07003075 private boolean isInCommunication() {
Nancy Chen0eb1e402014-08-21 22:52:29 -07003076 boolean IsInCall = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077
Tyler Gunnef9f6f92014-09-12 22:16:17 -07003078 TelecomManager telecomManager =
3079 (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
Eric Laurent38edfda2014-12-18 17:38:04 -08003080
3081 final long ident = Binder.clearCallingIdentity();
Tyler Gunnef9f6f92014-09-12 22:16:17 -07003082 IsInCall = telecomManager.isInCall();
Eric Laurent38edfda2014-12-18 17:38:04 -08003083 Binder.restoreCallingIdentity(ident);
Santos Cordon9eb45932014-06-27 12:28:43 -07003084
Nancy Chen0eb1e402014-08-21 22:52:29 -07003085 return (IsInCall || getMode() == AudioManager.MODE_IN_COMMUNICATION);
Eric Laurent6d517662012-04-23 18:42:39 -07003086 }
Eric Laurent25101b02011-02-02 09:33:30 -08003087
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003088 /**
3089 * For code clarity for getActiveStreamType(int)
3090 * @param delay_ms max time since last STREAM_MUSIC activity to consider
3091 * @return true if STREAM_MUSIC is active in streams handled by AudioFlinger now or
3092 * in the last "delay_ms" ms.
3093 */
3094 private boolean isAfMusicActiveRecently(int delay_ms) {
3095 return AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, delay_ms)
3096 || AudioSystem.isStreamActiveRemotely(AudioSystem.STREAM_MUSIC, delay_ms);
3097 }
3098
Eric Laurent6d517662012-04-23 18:42:39 -07003099 private int getActiveStreamType(int suggestedStreamType) {
Eric Laurent212532b2014-07-21 15:43:18 -07003100 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -05003101 case AudioSystem.PLATFORM_VOICE:
Eric Laurent6d517662012-04-23 18:42:39 -07003102 if (isInCommunication()) {
Eric Laurent25101b02011-02-02 09:33:30 -08003103 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
3104 == AudioSystem.FORCE_BT_SCO) {
3105 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
3106 return AudioSystem.STREAM_BLUETOOTH_SCO;
3107 } else {
3108 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
3109 return AudioSystem.STREAM_VOICE_CALL;
3110 }
Eric Laurent25101b02011-02-02 09:33:30 -08003111 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003112 if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003113 if (DEBUG_VOL)
3114 Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
3115 return AudioSystem.STREAM_MUSIC;
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003116 } else {
3117 if (DEBUG_VOL)
3118 Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING b/c default");
3119 return AudioSystem.STREAM_RING;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003120 }
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003121 } else if (isAfMusicActiveRecently(0)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003122 if (DEBUG_VOL)
3123 Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
3124 return AudioSystem.STREAM_MUSIC;
Eric Laurent25101b02011-02-02 09:33:30 -08003125 }
Eric Laurent212532b2014-07-21 15:43:18 -07003126 break;
John Spurlock61560172015-02-06 19:46:04 -05003127 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -07003128 if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
RoboErik2811dd32014-08-12 09:48:13 -07003129 // TV always defaults to STREAM_MUSIC
Eric Laurent212532b2014-07-21 15:43:18 -07003130 return AudioSystem.STREAM_MUSIC;
Eric Laurent212532b2014-07-21 15:43:18 -07003131 }
3132 break;
3133 default:
Eric Laurent6d517662012-04-23 18:42:39 -07003134 if (isInCommunication()) {
Eric Laurent25101b02011-02-02 09:33:30 -08003135 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
3136 == AudioSystem.FORCE_BT_SCO) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003137 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO");
Eric Laurent25101b02011-02-02 09:33:30 -08003138 return AudioSystem.STREAM_BLUETOOTH_SCO;
3139 } else {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003140 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL");
Eric Laurent25101b02011-02-02 09:33:30 -08003141 return AudioSystem.STREAM_VOICE_CALL;
3142 }
3143 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003144 StreamOverride.sDelayMs) ||
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003145 AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003146 StreamOverride.sDelayMs)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003147 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION");
Eric Laurent25101b02011-02-02 09:33:30 -08003148 return AudioSystem.STREAM_NOTIFICATION;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003149 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003150 if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003151 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: forcing STREAM_MUSIC");
3152 return AudioSystem.STREAM_MUSIC;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003153 } else {
John Spurlockeb1d88d2014-07-19 14:49:19 -04003154 if (DEBUG_VOL) Log.v(TAG,
3155 "getActiveStreamType: using STREAM_NOTIFICATION as default");
3156 return AudioSystem.STREAM_NOTIFICATION;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003157 }
Joe Onoratoc7fcba42011-01-05 16:53:11 -08003158 }
Eric Laurent212532b2014-07-21 15:43:18 -07003159 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 }
Eric Laurent212532b2014-07-21 15:43:18 -07003161 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Returning suggested type "
3162 + suggestedStreamType);
3163 return suggestedStreamType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 }
3165
John Spurlockbcc10872014-11-28 15:29:21 -05003166 private void broadcastRingerMode(String action, int ringerMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 // Send sticky broadcast
John Spurlockbcc10872014-11-28 15:29:21 -05003168 Intent broadcast = new Intent(action);
Glenn Kastenba195eb2011-12-13 09:30:40 -08003169 broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, ringerMode);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08003170 broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
3171 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003172 sendStickyBroadcastToAll(broadcast);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 }
3174
3175 private void broadcastVibrateSetting(int vibrateType) {
3176 // Send broadcast
3177 if (ActivityManagerNative.isSystemReady()) {
3178 Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
3179 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
3180 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003181 sendBroadcastToAll(broadcast);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 }
3183 }
3184
3185 // Message helper methods
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003186 /**
3187 * Queue a message on the given handler's message queue, after acquiring the service wake lock.
3188 * Note that the wake lock needs to be released after the message has been handled.
3189 */
3190 private void queueMsgUnderWakeLock(Handler handler, int msg,
3191 int arg1, int arg2, Object obj, int delay) {
Eric Laurenta4dfbdc52013-10-01 11:53:51 -07003192 final long ident = Binder.clearCallingIdentity();
3193 // Always acquire the wake lock as AudioService because it is released by the
3194 // message handler.
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07003195 mAudioEventWakeLock.acquire();
Eric Laurenta4dfbdc52013-10-01 11:53:51 -07003196 Binder.restoreCallingIdentity(ident);
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003197 sendMsg(handler, msg, SENDMSG_QUEUE, arg1, arg2, obj, delay);
3198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199
Eric Laurentafbb0472011-12-15 09:04:23 -08003200 private static void sendMsg(Handler handler, int msg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202
3203 if (existingMsgPolicy == SENDMSG_REPLACE) {
3204 handler.removeMessages(msg);
3205 } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
3206 return;
3207 }
Eric Laurentadbe8bf2014-11-03 18:26:32 -08003208 synchronized (mLastDeviceConnectMsgTime) {
3209 long time = SystemClock.uptimeMillis() + delay;
3210 handler.sendMessageAtTime(handler.obtainMessage(msg, arg1, arg2, obj), time);
3211 if (msg == MSG_SET_WIRED_DEVICE_CONNECTION_STATE ||
3212 msg == MSG_SET_A2DP_SRC_CONNECTION_STATE ||
3213 msg == MSG_SET_A2DP_SINK_CONNECTION_STATE) {
3214 mLastDeviceConnectMsgTime = time;
3215 }
3216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 }
3218
3219 boolean checkAudioSettingsPermission(String method) {
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07003220 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 == PackageManager.PERMISSION_GRANTED) {
3222 return true;
3223 }
3224 String msg = "Audio Settings Permission Denial: " + method + " from pid="
3225 + Binder.getCallingPid()
3226 + ", uid=" + Binder.getCallingUid();
3227 Log.w(TAG, msg);
3228 return false;
3229 }
3230
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003231 private int getDeviceForStream(int stream) {
3232 int device = AudioSystem.getDevicesForStream(stream);
3233 if ((device & (device - 1)) != 0) {
3234 // Multiple device selection is either:
3235 // - speaker + one other device: give priority to speaker in this case.
3236 // - one A2DP device + another device: happens with duplicated output. In this case
3237 // retain the device on the A2DP output as the other must not correspond to an active
3238 // selection if not the speaker.
Jungshik Jangc9ff9682014-09-15 17:41:06 +09003239 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003240 if ((device & AudioSystem.DEVICE_OUT_SPEAKER) != 0) {
3241 device = AudioSystem.DEVICE_OUT_SPEAKER;
Jungshik Jangc9ff9682014-09-15 17:41:06 +09003242 } else if ((device & AudioSystem.DEVICE_OUT_HDMI_ARC) != 0) {
3243 device = AudioSystem.DEVICE_OUT_HDMI_ARC;
3244 } else if ((device & AudioSystem.DEVICE_OUT_SPDIF) != 0) {
3245 device = AudioSystem.DEVICE_OUT_SPDIF;
3246 } else if ((device & AudioSystem.DEVICE_OUT_AUX_LINE) != 0) {
3247 device = AudioSystem.DEVICE_OUT_AUX_LINE;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003248 } else {
3249 device &= AudioSystem.DEVICE_OUT_ALL_A2DP;
3250 }
3251 }
3252 return device;
3253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254
Paul McLean10804eb2015-01-28 11:16:35 -08003255 /*
3256 * A class just for packaging up a set of connection parameters.
3257 */
3258 private class WiredDeviceConnectionState {
3259 public int mType;
3260 public int mState;
3261 public String mAddress;
3262 public String mName;
3263
3264 public WiredDeviceConnectionState(int type, int state, String address, String name) {
3265 mType = type;
3266 mState = state;
3267 mAddress = address;
3268 mName = name;
3269 }
3270 }
3271
3272 public void setWiredDeviceConnectionState(int type, int state, String address,
3273 String name) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003274 synchronized (mConnectedDevices) {
Paul McLean10804eb2015-01-28 11:16:35 -08003275 int delay = checkSendBecomingNoisyIntent(type, state);
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003276 queueMsgUnderWakeLock(mAudioHandler,
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003277 MSG_SET_WIRED_DEVICE_CONNECTION_STATE,
Paul McLean10804eb2015-01-28 11:16:35 -08003278 0,
3279 0,
3280 new WiredDeviceConnectionState(type, state, address, name),
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003281 delay);
3282 }
3283 }
3284
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003285 public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state, int profile)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003286 {
3287 int delay;
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003288 if (profile != BluetoothProfile.A2DP && profile != BluetoothProfile.A2DP_SINK) {
3289 throw new IllegalArgumentException("invalid profile " + profile);
3290 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003291 synchronized (mConnectedDevices) {
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003292 if (profile == BluetoothProfile.A2DP) {
3293 delay = checkSendBecomingNoisyIntent(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
3294 (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
3295 } else {
3296 delay = 0;
3297 }
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003298 queueMsgUnderWakeLock(mAudioHandler,
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003299 (profile == BluetoothProfile.A2DP ?
3300 MSG_SET_A2DP_SINK_CONNECTION_STATE : MSG_SET_A2DP_SRC_CONNECTION_STATE),
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003301 state,
3302 0,
3303 device,
3304 delay);
3305 }
3306 return delay;
3307 }
3308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 ///////////////////////////////////////////////////////////////////////////
3310 // Inner classes
3311 ///////////////////////////////////////////////////////////////////////////
3312
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003313 // NOTE: Locking order for synchronized objects related to volume or ringer mode management:
3314 // 1 mScoclient OR mSafeMediaVolumeState
3315 // 2 mSetModeDeathHandlers
3316 // 3 mSettingsLock
3317 // 4 VolumeStreamState.class
3318 // 5 mCameraSoundForced
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 public class VolumeStreamState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 private final int mStreamType;
3321
RoboErik4197cb62015-01-21 15:45:32 -08003322 private boolean mIsMuted;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07003323 private String mVolumeIndexSettingName;
Eric Laurenta553c252009-07-17 12:17:14 -07003324 private int mIndexMax;
John Spurlock2bb02ec2015-03-02 13:13:06 -05003325 private final SparseIntArray mIndexMap = new SparseIntArray(8);
John Spurlockf63860c2015-02-19 09:46:27 -05003326 private final Intent mVolumeChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327
Eric Laurenta553c252009-07-17 12:17:14 -07003328 private VolumeStreamState(String settingName, int streamType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003330 mVolumeIndexSettingName = settingName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331
3332 mStreamType = streamType;
Jared Suttles59820132009-08-13 21:50:52 -05003333 mIndexMax = MAX_STREAM_VOLUME[streamType];
Eric Laurenta553c252009-07-17 12:17:14 -07003334 AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
3335 mIndexMax *= 10;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003336
Eric Laurent33902db2012-10-07 16:15:07 -07003337 readSettings();
John Spurlockf63860c2015-02-19 09:46:27 -05003338 mVolumeChanged = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
3339 mVolumeChanged.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, mStreamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 }
3341
Eric Laurent42b041e2013-03-29 11:36:03 -07003342 public String getSettingNameForDevice(int device) {
3343 String name = mVolumeIndexSettingName;
Eric Laurent948d3272014-05-16 15:18:45 -07003344 String suffix = AudioSystem.getOutputDeviceName(device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003345 if (suffix.isEmpty()) {
3346 return name;
3347 }
3348 return name + "_" + suffix;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07003349 }
3350
Eric Laurentfdbee862014-05-12 15:26:12 -07003351 public void readSettings() {
3352 synchronized (VolumeStreamState.class) {
John Spurlockee5ad722015-03-03 16:17:21 -05003353 // force maximum volume on all streams if fixed volume property is set
3354 if (mUseFixedVolume) {
John Spurlock2bb02ec2015-03-02 13:13:06 -05003355 mIndexMap.put(AudioSystem.DEVICE_OUT_DEFAULT, mIndexMax);
Eric Laurentfdbee862014-05-12 15:26:12 -07003356 return;
3357 }
3358 // do not read system stream volume from settings: this stream is always aliased
3359 // to another stream type and its volume is never persisted. Values in settings can
3360 // only be stale values
3361 if ((mStreamType == AudioSystem.STREAM_SYSTEM) ||
3362 (mStreamType == AudioSystem.STREAM_SYSTEM_ENFORCED)) {
John Spurlock61560172015-02-06 19:46:04 -05003363 int index = 10 * AudioSystem.DEFAULT_STREAM_VOLUME[mStreamType];
Eric Laurentfdbee862014-05-12 15:26:12 -07003364 synchronized (mCameraSoundForced) {
3365 if (mCameraSoundForced) {
3366 index = mIndexMax;
3367 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003368 }
John Spurlock2bb02ec2015-03-02 13:13:06 -05003369 mIndexMap.put(AudioSystem.DEVICE_OUT_DEFAULT, index);
Eric Laurentfdbee862014-05-12 15:26:12 -07003370 return;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003371 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003372
Eric Laurentfdbee862014-05-12 15:26:12 -07003373 int remainingDevices = AudioSystem.DEVICE_OUT_ALL;
3374
3375 for (int i = 0; remainingDevices != 0; i++) {
3376 int device = (1 << i);
3377 if ((device & remainingDevices) == 0) {
3378 continue;
3379 }
3380 remainingDevices &= ~device;
3381
3382 // retrieve current volume for device
3383 String name = getSettingNameForDevice(device);
3384 // if no volume stored for current stream and device, use default volume if default
3385 // device, continue otherwise
3386 int defaultIndex = (device == AudioSystem.DEVICE_OUT_DEFAULT) ?
John Spurlock61560172015-02-06 19:46:04 -05003387 AudioSystem.DEFAULT_STREAM_VOLUME[mStreamType] : -1;
Eric Laurentfdbee862014-05-12 15:26:12 -07003388 int index = Settings.System.getIntForUser(
3389 mContentResolver, name, defaultIndex, UserHandle.USER_CURRENT);
3390 if (index == -1) {
3391 continue;
3392 }
3393
John Spurlock2bb02ec2015-03-02 13:13:06 -05003394 mIndexMap.put(device, getValidIndex(10 * index));
Eric Laurentdd45d012012-10-08 09:04:34 -07003395 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
3398
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003399 // must be called while synchronized VolumeStreamState.class
3400 public void applyDeviceVolume_syncVSS(int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003401 int index;
RoboErik4197cb62015-01-21 15:45:32 -08003402 if (mIsMuted) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003403 index = 0;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003404 } else if (((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 && mAvrcpAbsVolSupported)
3405 || ((device & mFullVolumeDevices) != 0)) {
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07003406 index = (mIndexMax + 5)/10;
Eric Laurentcd772d02013-10-30 18:31:07 -07003407 } else {
Eric Laurent42b041e2013-03-29 11:36:03 -07003408 index = (getIndex(device) + 5)/10;
3409 }
3410 AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412
Eric Laurentfdbee862014-05-12 15:26:12 -07003413 public void applyAllVolumes() {
3414 synchronized (VolumeStreamState.class) {
3415 // apply default volume first: by convention this will reset all
3416 // devices volumes in audio policy manager to the supplied value
3417 int index;
RoboErik4197cb62015-01-21 15:45:32 -08003418 if (mIsMuted) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003419 index = 0;
3420 } else {
3421 index = (getIndex(AudioSystem.DEVICE_OUT_DEFAULT) + 5)/10;
3422 }
3423 AudioSystem.setStreamVolumeIndex(mStreamType, index, AudioSystem.DEVICE_OUT_DEFAULT);
3424 // then apply device specific volumes
John Spurlock2bb02ec2015-03-02 13:13:06 -05003425 for (int i = 0; i < mIndexMap.size(); i++) {
3426 int device = mIndexMap.keyAt(i);
Eric Laurentfdbee862014-05-12 15:26:12 -07003427 if (device != AudioSystem.DEVICE_OUT_DEFAULT) {
RoboErik4197cb62015-01-21 15:45:32 -08003428 if (mIsMuted) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003429 index = 0;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003430 } else if (((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
3431 mAvrcpAbsVolSupported)
3432 || ((device & mFullVolumeDevices) != 0))
3433 {
Eric Laurentfdbee862014-05-12 15:26:12 -07003434 index = (mIndexMax + 5)/10;
3435 } else {
John Spurlock2bb02ec2015-03-02 13:13:06 -05003436 index = (mIndexMap.valueAt(i) + 5)/10;
Eric Laurentfdbee862014-05-12 15:26:12 -07003437 }
3438 AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
Eric Laurent42b041e2013-03-29 11:36:03 -07003439 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003440 }
3441 }
3442 }
3443
3444 public boolean adjustIndex(int deltaIndex, int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003445 return setIndex(getIndex(device) + deltaIndex,
3446 device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003447 }
3448
Eric Laurentfdbee862014-05-12 15:26:12 -07003449 public boolean setIndex(int index, int device) {
John Spurlockf63860c2015-02-19 09:46:27 -05003450 boolean changed = false;
3451 int oldIndex;
Eric Laurentfdbee862014-05-12 15:26:12 -07003452 synchronized (VolumeStreamState.class) {
John Spurlockf63860c2015-02-19 09:46:27 -05003453 oldIndex = getIndex(device);
Eric Laurentfdbee862014-05-12 15:26:12 -07003454 index = getValidIndex(index);
3455 synchronized (mCameraSoundForced) {
3456 if ((mStreamType == AudioSystem.STREAM_SYSTEM_ENFORCED) && mCameraSoundForced) {
3457 index = mIndexMax;
Eric Laurenta553c252009-07-17 12:17:14 -07003458 }
3459 }
John Spurlock2bb02ec2015-03-02 13:13:06 -05003460 mIndexMap.put(device, index);
Eric Laurentfdbee862014-05-12 15:26:12 -07003461
John Spurlockf63860c2015-02-19 09:46:27 -05003462 changed = oldIndex != index;
3463 if (changed) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003464 // Apply change to all streams using this one as alias
3465 // if changing volume of current device, also change volume of current
3466 // device on aliased stream
3467 boolean currentDevice = (device == getDeviceForStream(mStreamType));
3468 int numStreamTypes = AudioSystem.getNumStreamTypes();
3469 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3470 if (streamType != mStreamType &&
3471 mStreamVolumeAlias[streamType] == mStreamType) {
3472 int scaledIndex = rescaleIndex(index, mStreamType, streamType);
3473 mStreamStates[streamType].setIndex(scaledIndex,
3474 device);
3475 if (currentDevice) {
3476 mStreamStates[streamType].setIndex(scaledIndex,
3477 getDeviceForStream(streamType));
3478 }
3479 }
3480 }
Eric Laurentfdbee862014-05-12 15:26:12 -07003481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 }
John Spurlockf63860c2015-02-19 09:46:27 -05003483 if (changed) {
3484 oldIndex = (oldIndex + 5) / 10;
3485 index = (index + 5) / 10;
3486 mVolumeChanged.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
3487 mVolumeChanged.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
3488 sendBroadcastToAll(mVolumeChanged);
3489 }
3490 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 }
3492
Eric Laurentfdbee862014-05-12 15:26:12 -07003493 public int getIndex(int device) {
3494 synchronized (VolumeStreamState.class) {
John Spurlock2bb02ec2015-03-02 13:13:06 -05003495 int index = mIndexMap.get(device, -1);
3496 if (index == -1) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003497 // there is always an entry for AudioSystem.DEVICE_OUT_DEFAULT
John Spurlock2bb02ec2015-03-02 13:13:06 -05003498 index = mIndexMap.get(AudioSystem.DEVICE_OUT_DEFAULT);
Eric Laurentfdbee862014-05-12 15:26:12 -07003499 }
John Spurlock2bb02ec2015-03-02 13:13:06 -05003500 return index;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003501 }
Eric Laurent5b4e6542010-03-19 20:02:21 -07003502 }
3503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 public int getMaxIndex() {
Eric Laurenta553c252009-07-17 12:17:14 -07003505 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 }
3507
Eric Laurentfdbee862014-05-12 15:26:12 -07003508 public void setAllIndexes(VolumeStreamState srcStream) {
3509 synchronized (VolumeStreamState.class) {
3510 int srcStreamType = srcStream.getStreamType();
3511 // apply default device volume from source stream to all devices first in case
3512 // some devices are present in this stream state but not in source stream state
3513 int index = srcStream.getIndex(AudioSystem.DEVICE_OUT_DEFAULT);
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003514 index = rescaleIndex(index, srcStreamType, mStreamType);
John Spurlock2bb02ec2015-03-02 13:13:06 -05003515 for (int i = 0; i < mIndexMap.size(); i++) {
3516 mIndexMap.put(mIndexMap.keyAt(i), index);
Eric Laurentfdbee862014-05-12 15:26:12 -07003517 }
3518 // Now apply actual volume for devices in source stream state
John Spurlock2bb02ec2015-03-02 13:13:06 -05003519 SparseIntArray srcMap = srcStream.mIndexMap;
3520 for (int i = 0; i < srcMap.size(); i++) {
3521 int device = srcMap.keyAt(i);
3522 index = srcMap.valueAt(i);
Eric Laurentfdbee862014-05-12 15:26:12 -07003523 index = rescaleIndex(index, srcStreamType, mStreamType);
Eric Laurent33902db2012-10-07 16:15:07 -07003524
Eric Laurentfdbee862014-05-12 15:26:12 -07003525 setIndex(index, device);
3526 }
Eric Laurent6d517662012-04-23 18:42:39 -07003527 }
3528 }
3529
Eric Laurentfdbee862014-05-12 15:26:12 -07003530 public void setAllIndexesToMax() {
3531 synchronized (VolumeStreamState.class) {
John Spurlock2bb02ec2015-03-02 13:13:06 -05003532 for (int i = 0; i < mIndexMap.size(); i++) {
3533 mIndexMap.put(mIndexMap.keyAt(i), mIndexMax);
Eric Laurentfdbee862014-05-12 15:26:12 -07003534 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003535 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003536 }
3537
RoboErik4197cb62015-01-21 15:45:32 -08003538 public void mute(boolean state) {
John Spurlock22b9ee12015-02-18 22:51:44 -05003539 boolean changed = false;
Eric Laurentfdbee862014-05-12 15:26:12 -07003540 synchronized (VolumeStreamState.class) {
RoboErik4197cb62015-01-21 15:45:32 -08003541 if (state != mIsMuted) {
John Spurlock22b9ee12015-02-18 22:51:44 -05003542 changed = true;
RoboErik4197cb62015-01-21 15:45:32 -08003543 mIsMuted = state;
John Spurlock22b9ee12015-02-18 22:51:44 -05003544
RoboErik4197cb62015-01-21 15:45:32 -08003545 // Set the new mute volume. This propagates the values to
3546 // the audio system, otherwise the volume won't be changed
3547 // at the lower level.
3548 sendMsg(mAudioHandler,
3549 MSG_SET_ALL_VOLUMES,
3550 SENDMSG_QUEUE,
3551 0,
3552 0,
3553 this, 0);
Eric Laurentfdbee862014-05-12 15:26:12 -07003554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 }
John Spurlock22b9ee12015-02-18 22:51:44 -05003556 if (changed) {
3557 // Stream mute changed, fire the intent.
3558 Intent intent = new Intent(AudioManager.STREAM_MUTE_CHANGED_ACTION);
3559 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, mStreamType);
3560 intent.putExtra(AudioManager.EXTRA_STREAM_VOLUME_MUTED, state);
3561 sendBroadcastToAll(intent);
3562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 }
3564
Eric Laurent6d517662012-04-23 18:42:39 -07003565 public int getStreamType() {
3566 return mStreamType;
3567 }
3568
Eric Laurent212532b2014-07-21 15:43:18 -07003569 public void checkFixedVolumeDevices() {
3570 synchronized (VolumeStreamState.class) {
3571 // ignore settings for fixed volume devices: volume should always be at max or 0
3572 if (mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_MUSIC) {
John Spurlock2bb02ec2015-03-02 13:13:06 -05003573 for (int i = 0; i < mIndexMap.size(); i++) {
3574 int device = mIndexMap.keyAt(i);
3575 int index = mIndexMap.valueAt(i);
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003576 if (((device & mFullVolumeDevices) != 0)
3577 || (((device & mFixedVolumeDevices) != 0) && index != 0)) {
John Spurlock2bb02ec2015-03-02 13:13:06 -05003578 mIndexMap.put(device, mIndexMax);
Eric Laurent212532b2014-07-21 15:43:18 -07003579 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003580 applyDeviceVolume_syncVSS(device);
Eric Laurent212532b2014-07-21 15:43:18 -07003581 }
3582 }
3583 }
3584 }
3585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 private int getValidIndex(int index) {
3587 if (index < 0) {
3588 return 0;
John Spurlockee5ad722015-03-03 16:17:21 -05003589 } else if (mUseFixedVolume || index > mIndexMax) {
Eric Laurenta553c252009-07-17 12:17:14 -07003590 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 }
3592
3593 return index;
3594 }
3595
Eric Laurentbffc3d12012-05-07 17:43:49 -07003596 private void dump(PrintWriter pw) {
RoboErik4197cb62015-01-21 15:45:32 -08003597 pw.print(" Muted: ");
3598 pw.println(mIsMuted);
John Spurlock2b29bc42014-08-26 16:40:35 -04003599 pw.print(" Max: ");
3600 pw.println((mIndexMax + 5) / 10);
Eric Laurentbffc3d12012-05-07 17:43:49 -07003601 pw.print(" Current: ");
John Spurlock2bb02ec2015-03-02 13:13:06 -05003602 for (int i = 0; i < mIndexMap.size(); i++) {
3603 if (i > 0) {
3604 pw.print(", ");
3605 }
3606 final int device = mIndexMap.keyAt(i);
John Spurlock2b29bc42014-08-26 16:40:35 -04003607 pw.print(Integer.toHexString(device));
3608 final String deviceName = device == AudioSystem.DEVICE_OUT_DEFAULT ? "default"
3609 : AudioSystem.getOutputDeviceName(device);
3610 if (!deviceName.isEmpty()) {
3611 pw.print(" (");
3612 pw.print(deviceName);
3613 pw.print(")");
3614 }
3615 pw.print(": ");
John Spurlock2bb02ec2015-03-02 13:13:06 -05003616 final int index = (mIndexMap.valueAt(i) + 5) / 10;
John Spurlock2b29bc42014-08-26 16:40:35 -04003617 pw.print(index);
Eric Laurentbffc3d12012-05-07 17:43:49 -07003618 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 }
3621
3622 /** Thread that handles native AudioSystem control. */
3623 private class AudioSystemThread extends Thread {
3624 AudioSystemThread() {
3625 super("AudioService");
3626 }
3627
3628 @Override
3629 public void run() {
3630 // Set this thread up so the handler will work on it
3631 Looper.prepare();
3632
3633 synchronized(AudioService.this) {
3634 mAudioHandler = new AudioHandler();
3635
3636 // Notify that the handler has been created
3637 AudioService.this.notify();
3638 }
3639
3640 // Listen for volume change requests that are set by VolumePanel
3641 Looper.loop();
3642 }
3643 }
3644
3645 /** Handles internal volume messages in separate volume thread. */
3646 private class AudioHandler extends Handler {
3647
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003648 private void setDeviceVolume(VolumeStreamState streamState, int device) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003650 synchronized (VolumeStreamState.class) {
3651 // Apply volume
3652 streamState.applyDeviceVolume_syncVSS(device);
Eric Laurenta553c252009-07-17 12:17:14 -07003653
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003654 // Apply change to all streams using this one as alias
3655 int numStreamTypes = AudioSystem.getNumStreamTypes();
3656 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3657 if (streamType != streamState.mStreamType &&
3658 mStreamVolumeAlias[streamType] == streamState.mStreamType) {
3659 // Make sure volume is also maxed out on A2DP device for aliased stream
3660 // that may have a different device selected
3661 int streamDevice = getDeviceForStream(streamType);
3662 if ((device != streamDevice) && mAvrcpAbsVolSupported &&
3663 ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0)) {
3664 mStreamStates[streamType].applyDeviceVolume_syncVSS(device);
3665 }
3666 mStreamStates[streamType].applyDeviceVolume_syncVSS(streamDevice);
Eric Laurentcd772d02013-10-30 18:31:07 -07003667 }
Eric Laurenta553c252009-07-17 12:17:14 -07003668 }
3669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 // Post a persist volume msg
Eric Laurentafbb0472011-12-15 09:04:23 -08003671 sendMsg(mAudioHandler,
3672 MSG_PERSIST_VOLUME,
Eric Laurent98ad9b92012-02-15 17:21:37 -08003673 SENDMSG_QUEUE,
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003674 device,
Eric Laurent42b041e2013-03-29 11:36:03 -07003675 0,
Eric Laurentafbb0472011-12-15 09:04:23 -08003676 streamState,
3677 PERSIST_DELAY);
3678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
3680
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003681 private void setAllVolumes(VolumeStreamState streamState) {
3682
3683 // Apply volume
3684 streamState.applyAllVolumes();
3685
3686 // Apply change to all streams using this one as alias
3687 int numStreamTypes = AudioSystem.getNumStreamTypes();
3688 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3689 if (streamType != streamState.mStreamType &&
Eric Laurent6d517662012-04-23 18:42:39 -07003690 mStreamVolumeAlias[streamType] == streamState.mStreamType) {
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003691 mStreamStates[streamType].applyAllVolumes();
3692 }
3693 }
3694 }
3695
Eric Laurent42b041e2013-03-29 11:36:03 -07003696 private void persistVolume(VolumeStreamState streamState, int device) {
Eric Laurent83a017b2013-03-19 18:15:31 -07003697 if (mUseFixedVolume) {
3698 return;
3699 }
Eric Laurent212532b2014-07-21 15:43:18 -07003700 if (isPlatformTelevision() && (streamState.mStreamType != AudioSystem.STREAM_MUSIC)) {
3701 return;
3702 }
Eric Laurent42b041e2013-03-29 11:36:03 -07003703 System.putIntForUser(mContentResolver,
3704 streamState.getSettingNameForDevice(device),
3705 (streamState.getIndex(device) + 5)/ 10,
3706 UserHandle.USER_CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 }
3708
Glenn Kastenba195eb2011-12-13 09:30:40 -08003709 private void persistRingerMode(int ringerMode) {
Eric Laurent83a017b2013-03-19 18:15:31 -07003710 if (mUseFixedVolume) {
3711 return;
3712 }
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07003713 Settings.Global.putInt(mContentResolver, Settings.Global.MODE_RINGER, ringerMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 }
3715
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003716 private boolean onLoadSoundEffects() {
3717 int status;
3718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 synchronized (mSoundEffectsLock) {
Eric Laurent4a5eeb92014-05-06 10:49:04 -07003720 if (!mSystemReady) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003721 Log.w(TAG, "onLoadSoundEffects() called before boot complete");
3722 return false;
3723 }
3724
3725 if (mSoundPool != null) {
3726 return true;
3727 }
3728
3729 loadTouchSoundAssets();
3730
Jean-Michel Trivi55a30c42014-07-20 17:56:11 -07003731 mSoundPool = new SoundPool.Builder()
3732 .setMaxStreams(NUM_SOUNDPOOL_CHANNELS)
3733 .setAudioAttributes(new AudioAttributes.Builder()
3734 .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
3735 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
3736 .build())
3737 .build();
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003738 mSoundPoolCallBack = null;
3739 mSoundPoolListenerThread = new SoundPoolListenerThread();
3740 mSoundPoolListenerThread.start();
3741 int attempts = 3;
3742 while ((mSoundPoolCallBack == null) && (attempts-- > 0)) {
3743 try {
3744 // Wait for mSoundPoolCallBack to be set by the other thread
Glenn Kasten167d1a22013-07-23 16:24:41 -07003745 mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003746 } catch (InterruptedException e) {
3747 Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
3748 }
3749 }
3750
3751 if (mSoundPoolCallBack == null) {
3752 Log.w(TAG, "onLoadSoundEffects() SoundPool listener or thread creation error");
3753 if (mSoundPoolLooper != null) {
3754 mSoundPoolLooper.quit();
3755 mSoundPoolLooper = null;
3756 }
3757 mSoundPoolListenerThread = null;
3758 mSoundPool.release();
3759 mSoundPool = null;
3760 return false;
3761 }
3762 /*
3763 * poolId table: The value -1 in this table indicates that corresponding
3764 * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
3765 * Once loaded, the value in poolId is the sample ID and the same
3766 * sample can be reused for another effect using the same file.
3767 */
3768 int[] poolId = new int[SOUND_EFFECT_FILES.size()];
3769 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.size(); fileIdx++) {
3770 poolId[fileIdx] = -1;
3771 }
3772 /*
3773 * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
3774 * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
3775 * this indicates we have a valid sample loaded for this effect.
3776 */
3777
3778 int numSamples = 0;
3779 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
3780 // Do not load sample if this effect uses the MediaPlayer
3781 if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
3782 continue;
3783 }
3784 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
3785 String filePath = Environment.getRootDirectory()
3786 + SOUND_EFFECTS_PATH
3787 + SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effect][0]);
3788 int sampleId = mSoundPool.load(filePath, 0);
3789 if (sampleId <= 0) {
3790 Log.w(TAG, "Soundpool could not load file: "+filePath);
3791 } else {
3792 SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
3793 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
3794 numSamples++;
3795 }
3796 } else {
3797 SOUND_EFFECT_FILES_MAP[effect][1] =
3798 poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
3799 }
3800 }
3801 // wait for all samples to be loaded
3802 if (numSamples > 0) {
3803 mSoundPoolCallBack.setSamples(poolId);
3804
3805 attempts = 3;
3806 status = 1;
3807 while ((status == 1) && (attempts-- > 0)) {
3808 try {
Glenn Kasten167d1a22013-07-23 16:24:41 -07003809 mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003810 status = mSoundPoolCallBack.status();
3811 } catch (InterruptedException e) {
3812 Log.w(TAG, "Interrupted while waiting sound pool callback.");
3813 }
3814 }
3815 } else {
3816 status = -1;
3817 }
3818
3819 if (mSoundPoolLooper != null) {
3820 mSoundPoolLooper.quit();
3821 mSoundPoolLooper = null;
3822 }
3823 mSoundPoolListenerThread = null;
3824 if (status != 0) {
3825 Log.w(TAG,
3826 "onLoadSoundEffects(), Error "+status+ " while loading samples");
3827 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
3828 if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) {
3829 SOUND_EFFECT_FILES_MAP[effect][1] = -1;
3830 }
3831 }
3832
3833 mSoundPool.release();
3834 mSoundPool = null;
3835 }
3836 }
3837 return (status == 0);
3838 }
3839
3840 /**
3841 * Unloads samples from the sound pool.
3842 * This method can be called to free some memory when
3843 * sound effects are disabled.
3844 */
3845 private void onUnloadSoundEffects() {
3846 synchronized (mSoundEffectsLock) {
3847 if (mSoundPool == null) {
3848 return;
3849 }
3850
3851 int[] poolId = new int[SOUND_EFFECT_FILES.size()];
3852 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.size(); fileIdx++) {
3853 poolId[fileIdx] = 0;
3854 }
3855
3856 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
3857 if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
3858 continue;
3859 }
3860 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
3861 mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
3862 SOUND_EFFECT_FILES_MAP[effect][1] = -1;
3863 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
3864 }
3865 }
3866 mSoundPool.release();
3867 mSoundPool = null;
3868 }
3869 }
3870
3871 private void onPlaySoundEffect(int effectType, int volume) {
3872 synchronized (mSoundEffectsLock) {
3873
3874 onLoadSoundEffects();
3875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 if (mSoundPool == null) {
3877 return;
3878 }
Eric Laurenta2ef57d2009-09-28 04:46:10 -07003879 float volFloat;
Eric Laurent25101b02011-02-02 09:33:30 -08003880 // use default if volume is not specified by caller
Eric Laurenta2ef57d2009-09-28 04:46:10 -07003881 if (volume < 0) {
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -07003882 volFloat = (float)Math.pow(10, (float)sSoundEffectVolumeDb/20);
Eric Laurenta2ef57d2009-09-28 04:46:10 -07003883 } else {
RoboErik8a2cfc32014-05-16 11:19:38 -07003884 volFloat = volume / 1000.0f;
Eric Laurenta2ef57d2009-09-28 04:46:10 -07003885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886
3887 if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003888 mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1],
3889 volFloat, volFloat, 0, 0, 1.0f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 } else {
3891 MediaPlayer mediaPlayer = new MediaPlayer();
Glenn Kasten62b9aec2011-11-07 11:10:16 -08003892 try {
Eric Laurente78fced2013-03-15 16:03:47 -07003893 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH +
3894 SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effectType][0]);
Glenn Kasten62b9aec2011-11-07 11:10:16 -08003895 mediaPlayer.setDataSource(filePath);
3896 mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
3897 mediaPlayer.prepare();
Glenn Kasten068225d2012-02-27 16:21:04 -08003898 mediaPlayer.setVolume(volFloat);
Glenn Kasten62b9aec2011-11-07 11:10:16 -08003899 mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
3900 public void onCompletion(MediaPlayer mp) {
3901 cleanupPlayer(mp);
3902 }
3903 });
3904 mediaPlayer.setOnErrorListener(new OnErrorListener() {
3905 public boolean onError(MediaPlayer mp, int what, int extra) {
3906 cleanupPlayer(mp);
3907 return true;
3908 }
3909 });
3910 mediaPlayer.start();
3911 } catch (IOException ex) {
3912 Log.w(TAG, "MediaPlayer IOException: "+ex);
3913 } catch (IllegalArgumentException ex) {
3914 Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
3915 } catch (IllegalStateException ex) {
3916 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 }
3918 }
3919 }
3920 }
3921
3922 private void cleanupPlayer(MediaPlayer mp) {
3923 if (mp != null) {
3924 try {
3925 mp.stop();
3926 mp.release();
3927 } catch (IllegalStateException ex) {
3928 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
3929 }
3930 }
3931 }
3932
Eric Laurentfa640152011-03-12 15:59:51 -08003933 private void setForceUse(int usage, int config) {
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08003934 synchronized (mConnectedDevices) {
3935 setForceUseInt_SyncDevices(usage, config);
3936 }
Eric Laurentfa640152011-03-12 15:59:51 -08003937 }
3938
Eric Laurent05274f32012-11-29 12:48:18 -08003939 private void onPersistSafeVolumeState(int state) {
3940 Settings.Global.putInt(mContentResolver,
3941 Settings.Global.AUDIO_SAFE_VOLUME_STATE,
3942 state);
3943 }
3944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 @Override
3946 public void handleMessage(Message msg) {
Eric Laurentafbb0472011-12-15 09:04:23 -08003947 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003949 case MSG_SET_DEVICE_VOLUME:
3950 setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);
3951 break;
3952
3953 case MSG_SET_ALL_VOLUMES:
3954 setAllVolumes((VolumeStreamState) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 break;
3956
3957 case MSG_PERSIST_VOLUME:
Eric Laurent42b041e2013-03-29 11:36:03 -07003958 persistVolume((VolumeStreamState) msg.obj, msg.arg1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 break;
3960
Justin Koh57978ed2012-04-03 17:37:58 -07003961 case MSG_PERSIST_MASTER_VOLUME_MUTE:
Eric Laurent83a017b2013-03-19 18:15:31 -07003962 if (mUseFixedVolume) {
3963 return;
3964 }
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07003965 Settings.System.putIntForUser(mContentResolver,
3966 Settings.System.VOLUME_MASTER_MUTE,
3967 msg.arg1,
Julia Reynoldsb53453f2014-08-22 11:42:43 -04003968 msg.arg2);
Justin Koh57978ed2012-04-03 17:37:58 -07003969 break;
3970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 case MSG_PERSIST_RINGER_MODE:
Glenn Kastenba195eb2011-12-13 09:30:40 -08003972 // note that the value persisted is the current ringer mode, not the
3973 // value of ringer mode as of the time the request was made to persist
John Spurlock661f2cf2014-11-17 10:29:10 -05003974 persistRingerMode(getRingerModeInternal());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 break;
3976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 case MSG_MEDIA_SERVER_DIED:
Eric Laurenteb4b8a22014-07-21 13:10:07 -07003978 if (!mSystemReady ||
3979 (AudioSystem.checkAudioFlinger() != AudioSystem.AUDIO_STATUS_OK)) {
Eric Laurent89e74ba2009-09-30 18:26:36 -07003980 Log.e(TAG, "Media server died.");
Eric Laurentafbb0472011-12-15 09:04:23 -08003981 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0,
Eric Laurent89e74ba2009-09-30 18:26:36 -07003982 null, 500);
Eric Laurentdfb881f2013-07-18 14:41:39 -07003983 break;
Eric Laurent89e74ba2009-09-30 18:26:36 -07003984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 Log.e(TAG, "Media server started.");
Eric Laurentdfb881f2013-07-18 14:41:39 -07003986
Eric Laurent3c652ca2010-06-21 20:46:26 -07003987 // indicate to audio HAL that we start the reconfiguration phase after a media
3988 // server crash
Eric Laurentdfb881f2013-07-18 14:41:39 -07003989 // Note that we only execute this when the media server
Eric Laurent3c652ca2010-06-21 20:46:26 -07003990 // process restarts after a crash, not the first time it is started.
3991 AudioSystem.setParameters("restarting=true");
3992
Glenn Kastenfd116ad2013-07-12 17:10:39 -07003993 readAndSetLowRamDevice();
3994
Eric Laurentc42ac9d2009-07-29 08:53:03 -07003995 // Restore device connection states
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08003996 synchronized (mConnectedDevices) {
3997 Set set = mConnectedDevices.entrySet();
3998 Iterator i = set.iterator();
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003999 while (i.hasNext()) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004000 Map.Entry device = (Map.Entry)i.next();
4001 AudioSystem.setDeviceConnectionState(
4002 ((Integer)device.getKey()).intValue(),
4003 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004004 (String)device.getValue(),
4005 "unknown-device");
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004006 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004007 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004008 // Restore call state
4009 AudioSystem.setPhoneState(mMode);
4010
Eric Laurentd5603c12009-08-06 08:49:39 -07004011 // Restore forced usage for communcations and record
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004012 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
Eric Laurentd5603c12009-08-06 08:49:39 -07004013 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
Eric Laurentdd45d012012-10-08 09:04:34 -07004014 AudioSystem.setForceUse(AudioSystem.FOR_SYSTEM, mCameraSoundForced ?
4015 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004016
Eric Laurenta553c252009-07-17 12:17:14 -07004017 // Restore stream volumes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 int numStreamTypes = AudioSystem.getNumStreamTypes();
4019 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004021 AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08004022
4023 streamState.applyAllVolumes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004025
4026 // Restore ringer mode
John Spurlock661f2cf2014-11-17 10:29:10 -05004027 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent3c652ca2010-06-21 20:46:26 -07004028
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004029 // Reset device orientation (if monitored for this device)
Eric Laurentd640bd32012-09-28 18:01:48 -07004030 if (mMonitorOrientation) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004031 setOrientationForAudioSystem();
4032 }
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07004033 if (mMonitorRotation) {
4034 setRotationForAudioSystem();
4035 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004036
Eric Laurent78472112012-05-21 08:57:21 -07004037 synchronized (mBluetoothA2dpEnabledLock) {
4038 AudioSystem.setForceUse(AudioSystem.FOR_MEDIA,
4039 mBluetoothA2dpEnabled ?
4040 AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP);
4041 }
Eric Laurentbff5ca52012-11-02 16:48:26 -07004042
4043 synchronized (mSettingsLock) {
4044 AudioSystem.setForceUse(AudioSystem.FOR_DOCK,
4045 mDockAudioMediaEnabled ?
4046 AudioSystem.FORCE_ANALOG_DOCK : AudioSystem.FORCE_NONE);
4047 }
Eric Laurent212532b2014-07-21 15:43:18 -07004048 if (mHdmiManager != null) {
4049 synchronized (mHdmiManager) {
4050 if (mHdmiTvClient != null) {
4051 setHdmiSystemAudioSupported(mHdmiSystemAudioSupported);
4052 }
4053 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09004054 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08004055
4056 synchronized (mAudioPolicies) {
4057 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
4058 policy.connectMixes();
4059 }
4060 }
4061
Eric Laurent3c652ca2010-06-21 20:46:26 -07004062 // indicate the end of reconfiguration phase to audio HAL
4063 AudioSystem.setParameters("restarting=false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 break;
4065
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004066 case MSG_UNLOAD_SOUND_EFFECTS:
4067 onUnloadSoundEffects();
4068 break;
4069
Eric Laurent117b7bb2011-01-16 17:07:27 -08004070 case MSG_LOAD_SOUND_EFFECTS:
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004071 //FIXME: onLoadSoundEffects() should be executed in a separate thread as it
4072 // can take several dozens of milliseconds to complete
4073 boolean loaded = onLoadSoundEffects();
4074 if (msg.obj != null) {
4075 LoadSoundEffectReply reply = (LoadSoundEffectReply)msg.obj;
4076 synchronized (reply) {
4077 reply.mStatus = loaded ? 0 : -1;
4078 reply.notify();
4079 }
4080 }
Eric Laurent117b7bb2011-01-16 17:07:27 -08004081 break;
4082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 case MSG_PLAY_SOUND_EFFECT:
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004084 onPlaySoundEffect(msg.arg1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 break;
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004086
4087 case MSG_BTA2DP_DOCK_TIMEOUT:
4088 // msg.obj == address of BTA2DP device
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004089 synchronized (mConnectedDevices) {
4090 makeA2dpDeviceUnavailableNow( (String) msg.obj );
4091 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004092 break;
Eric Laurentfa640152011-03-12 15:59:51 -08004093
4094 case MSG_SET_FORCE_USE:
Eric Laurentc390bed2012-07-03 12:24:05 -07004095 case MSG_SET_FORCE_BT_A2DP_USE:
Eric Laurentfa640152011-03-12 15:59:51 -08004096 setForceUse(msg.arg1, msg.arg2);
4097 break;
Jean-Michel Trivid589fea2011-04-15 11:28:10 -07004098
Eric Laurentdc03c612011-04-01 10:59:41 -07004099 case MSG_BT_HEADSET_CNCT_FAILED:
4100 resetBluetoothSco();
4101 break;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004102
4103 case MSG_SET_WIRED_DEVICE_CONNECTION_STATE:
Paul McLean10804eb2015-01-28 11:16:35 -08004104 { WiredDeviceConnectionState connectState =
4105 (WiredDeviceConnectionState)msg.obj;
4106 onSetWiredDeviceConnectionState(connectState.mType, connectState.mState,
4107 connectState.mAddress, connectState.mName);
4108 mAudioEventWakeLock.release();
4109 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004110 break;
4111
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004112 case MSG_SET_A2DP_SRC_CONNECTION_STATE:
4113 onSetA2dpSourceConnectionState((BluetoothDevice)msg.obj, msg.arg1);
4114 mAudioEventWakeLock.release();
4115 break;
4116
4117 case MSG_SET_A2DP_SINK_CONNECTION_STATE:
4118 onSetA2dpSinkConnectionState((BluetoothDevice)msg.obj, msg.arg1);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004119 mAudioEventWakeLock.release();
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004120 break;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004121
4122 case MSG_REPORT_NEW_ROUTES: {
4123 int N = mRoutesObservers.beginBroadcast();
4124 if (N > 0) {
4125 AudioRoutesInfo routes;
4126 synchronized (mCurAudioRoutes) {
4127 routes = new AudioRoutesInfo(mCurAudioRoutes);
4128 }
4129 while (N > 0) {
4130 N--;
4131 IAudioRoutesObserver obs = mRoutesObservers.getBroadcastItem(N);
4132 try {
4133 obs.dispatchAudioRoutesChanged(routes);
4134 } catch (RemoteException e) {
4135 }
4136 }
4137 }
4138 mRoutesObservers.finishBroadcast();
4139 break;
4140 }
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07004141
Eric Laurentc34dcc12012-09-10 13:51:52 -07004142 case MSG_CHECK_MUSIC_ACTIVE:
4143 onCheckMusicActive();
4144 break;
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004145
4146 case MSG_BROADCAST_AUDIO_BECOMING_NOISY:
4147 onSendBecomingNoisyIntent();
4148 break;
Eric Laurentd640bd32012-09-28 18:01:48 -07004149
4150 case MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED:
4151 case MSG_CONFIGURE_SAFE_MEDIA_VOLUME:
4152 onConfigureSafeVolume((msg.what == MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED));
4153 break;
Eric Laurent05274f32012-11-29 12:48:18 -08004154 case MSG_PERSIST_SAFE_VOLUME_STATE:
4155 onPersistSafeVolumeState(msg.arg1);
4156 break;
Jean-Michel Trivia578c482012-12-28 11:19:49 -08004157
Eric Laurent2a57ca92013-03-07 17:29:27 -08004158 case MSG_BROADCAST_BT_CONNECTION_STATE:
4159 onBroadcastScoConnectionState(msg.arg1);
4160 break;
Eric Laurent4a5eeb92014-05-06 10:49:04 -07004161
4162 case MSG_SYSTEM_READY:
4163 onSystemReady();
4164 break;
John Spurlockaa5ee4d2014-07-25 13:05:12 -04004165
4166 case MSG_PERSIST_MUSIC_ACTIVE_MS:
4167 final int musicActiveMs = msg.arg1;
4168 Settings.Secure.putIntForUser(mContentResolver,
4169 Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, musicActiveMs,
4170 UserHandle.USER_CURRENT);
4171 break;
Julia Reynoldsb53453f2014-08-22 11:42:43 -04004172 case MSG_PERSIST_MICROPHONE_MUTE:
4173 Settings.System.putIntForUser(mContentResolver,
4174 Settings.System.MICROPHONE_MUTE,
4175 msg.arg1,
4176 msg.arg2);
4177 break;
RoboErik5452e252015-02-06 15:33:53 -08004178 case MSG_UNMUTE_STREAM:
4179 onUnmuteStream(msg.arg1, msg.arg2);
4180 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 }
4182 }
4183 }
4184
Jason Parekhb1096152009-03-24 17:48:25 -07004185 private class SettingsObserver extends ContentObserver {
Eric Laurenta553c252009-07-17 12:17:14 -07004186
Jason Parekhb1096152009-03-24 17:48:25 -07004187 SettingsObserver() {
4188 super(new Handler());
4189 mContentResolver.registerContentObserver(Settings.System.getUriFor(
4190 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
Eric Laurent7ee1e4f2012-10-26 18:11:21 -07004191 mContentResolver.registerContentObserver(Settings.Global.getUriFor(
4192 Settings.Global.DOCK_AUDIO_MEDIA_ENABLED), false, this);
Jason Parekhb1096152009-03-24 17:48:25 -07004193 }
4194
4195 @Override
4196 public void onChange(boolean selfChange) {
4197 super.onChange(selfChange);
Glenn Kastenba195eb2011-12-13 09:30:40 -08004198 // FIXME This synchronized is not necessary if mSettingsLock only protects mRingerMode.
4199 // However there appear to be some missing locks around mRingerModeMutedStreams
4200 // and mRingerModeAffectedStreams, so will leave this synchronized for now.
4201 // mRingerModeMutedStreams and mMuteAffectedStreams are safe (only accessed once).
Eric Laurenta553c252009-07-17 12:17:14 -07004202 synchronized (mSettingsLock) {
Eric Laurent24e0d9b2013-10-03 18:15:07 -07004203 if (updateRingerModeAffectedStreams()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004204 /*
4205 * Ensure all stream types that should be affected by ringer mode
4206 * are in the proper state.
4207 */
John Spurlock661f2cf2014-11-17 10:29:10 -05004208 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurenta553c252009-07-17 12:17:14 -07004209 }
Eric Laurent7ee1e4f2012-10-26 18:11:21 -07004210 readDockAudioSettings(mContentResolver);
Eric Laurenta553c252009-07-17 12:17:14 -07004211 }
Jason Parekhb1096152009-03-24 17:48:25 -07004212 }
Jason Parekhb1096152009-03-24 17:48:25 -07004213 }
Eric Laurenta553c252009-07-17 12:17:14 -07004214
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004215 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004216 private void makeA2dpDeviceAvailable(String address) {
Eric Laurent78472112012-05-21 08:57:21 -07004217 // enable A2DP before notifying A2DP connection to avoid unecessary processing in
4218 // audio policy manager
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004219 VolumeStreamState streamState = mStreamStates[AudioSystem.STREAM_MUSIC];
4220 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
4221 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0, streamState, 0);
Eric Laurent78472112012-05-21 08:57:21 -07004222 setBluetoothA2dpOnInt(true);
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004223 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
4224 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004225 address,
4226 "a2dp-device");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004227 // Reset A2DP suspend state each time a new sink is connected
4228 AudioSystem.setParameters("A2dpSuspended=false");
4229 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
4230 address);
4231 }
4232
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004233 private void onSendBecomingNoisyIntent() {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004234 sendBroadcastToAll(new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
Mike Lockwood98418182012-05-10 17:13:20 -07004235 }
4236
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004237 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004238 private void makeA2dpDeviceUnavailableNow(String address) {
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004239 synchronized (mA2dpAvrcpLock) {
4240 mAvrcpAbsVolSupported = false;
4241 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004242 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
4243 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004244 address,
4245 "a2dp-device");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004246 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
RoboErik5535ea82014-09-25 14:53:16 -07004247 synchronized (mCurAudioRoutes) {
4248 // Remove A2DP routes as well
John Spurlock61560172015-02-06 19:46:04 -05004249 if (mCurAudioRoutes.bluetoothName != null) {
4250 mCurAudioRoutes.bluetoothName = null;
RoboErik5535ea82014-09-25 14:53:16 -07004251 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4252 SENDMSG_NOOP, 0, 0, null, 0);
4253 }
4254 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004255 }
4256
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004257 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004258 private void makeA2dpDeviceUnavailableLater(String address) {
Eric Laurent3b591262010-04-20 07:01:00 -07004259 // prevent any activity on the A2DP audio output to avoid unwanted
4260 // reconnection of the sink.
4261 AudioSystem.setParameters("A2dpSuspended=true");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004262 // the device will be made unavailable later, so consider it disconnected right away
4263 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
4264 // send the delayed message to make the device unavailable later
4265 Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
4266 mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
4267
4268 }
4269
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004270 // must be called synchronized on mConnectedDevices
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004271 private void makeA2dpSrcAvailable(String address) {
4272 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
4273 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004274 address,
4275 "a2dp-device");
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004276 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP),
4277 address);
4278 }
4279
4280 // must be called synchronized on mConnectedDevices
4281 private void makeA2dpSrcUnavailable(String address) {
4282 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
4283 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004284 address,
4285 "a2dp-device");
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004286 mConnectedDevices.remove(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP);
4287 }
4288
4289 // must be called synchronized on mConnectedDevices
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004290 private void cancelA2dpDeviceTimeout() {
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004291 mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
4292 }
4293
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004294 // must be called synchronized on mConnectedDevices
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004295 private boolean hasScheduledA2dpDockTimeout() {
4296 return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
4297 }
4298
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004299 private void onSetA2dpSinkConnectionState(BluetoothDevice btDevice, int state)
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004300 {
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004301 if (DEBUG_VOL) {
4302 Log.d(TAG, "onSetA2dpSinkConnectionState btDevice="+btDevice+"state="+state);
4303 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004304 if (btDevice == null) {
4305 return;
4306 }
4307 String address = btDevice.getAddress();
4308 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4309 address = "";
4310 }
John Du5a0cf7a2013-07-19 11:30:34 -07004311
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004312 synchronized (mConnectedDevices) {
4313 boolean isConnected =
4314 (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
4315 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
4316
4317 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
4318 if (btDevice.isBluetoothDock()) {
4319 if (state == BluetoothProfile.STATE_DISCONNECTED) {
4320 // introduction of a delay for transient disconnections of docks when
4321 // power is rapidly turned off/on, this message will be canceled if
4322 // we reconnect the dock under a preset delay
4323 makeA2dpDeviceUnavailableLater(address);
4324 // the next time isConnected is evaluated, it will be false for the dock
4325 }
4326 } else {
4327 makeA2dpDeviceUnavailableNow(address);
4328 }
Dianne Hackborn632ca412012-06-14 19:34:10 -07004329 synchronized (mCurAudioRoutes) {
John Spurlock61560172015-02-06 19:46:04 -05004330 if (mCurAudioRoutes.bluetoothName != null) {
4331 mCurAudioRoutes.bluetoothName = null;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004332 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4333 SENDMSG_NOOP, 0, 0, null, 0);
4334 }
4335 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004336 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
4337 if (btDevice.isBluetoothDock()) {
4338 // this could be a reconnection after a transient disconnection
4339 cancelA2dpDeviceTimeout();
4340 mDockAddress = address;
4341 } else {
4342 // this could be a connection of another A2DP device before the timeout of
4343 // a dock: cancel the dock timeout, and make the dock unavailable now
4344 if(hasScheduledA2dpDockTimeout()) {
4345 cancelA2dpDeviceTimeout();
4346 makeA2dpDeviceUnavailableNow(mDockAddress);
4347 }
4348 }
4349 makeA2dpDeviceAvailable(address);
Dianne Hackborn632ca412012-06-14 19:34:10 -07004350 synchronized (mCurAudioRoutes) {
4351 String name = btDevice.getAliasName();
John Spurlock61560172015-02-06 19:46:04 -05004352 if (!TextUtils.equals(mCurAudioRoutes.bluetoothName, name)) {
4353 mCurAudioRoutes.bluetoothName = name;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004354 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4355 SENDMSG_NOOP, 0, 0, null, 0);
4356 }
4357 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004358 }
4359 }
4360 }
4361
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004362 private void onSetA2dpSourceConnectionState(BluetoothDevice btDevice, int state)
4363 {
4364 if (DEBUG_VOL) {
4365 Log.d(TAG, "onSetA2dpSourceConnectionState btDevice="+btDevice+" state="+state);
4366 }
4367 if (btDevice == null) {
4368 return;
4369 }
4370 String address = btDevice.getAddress();
4371 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4372 address = "";
4373 }
4374
4375 synchronized (mConnectedDevices) {
4376 boolean isConnected =
4377 (mConnectedDevices.containsKey(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP) &&
4378 mConnectedDevices.get(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP).equals(address));
4379
4380 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
4381 makeA2dpSrcUnavailable(address);
4382 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
4383 makeA2dpSrcAvailable(address);
4384 }
4385 }
4386 }
4387
John Du5a0cf7a2013-07-19 11:30:34 -07004388 public void avrcpSupportsAbsoluteVolume(String address, boolean support) {
4389 // address is not used for now, but may be used when multiple a2dp devices are supported
4390 synchronized (mA2dpAvrcpLock) {
4391 mAvrcpAbsVolSupported = support;
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004392 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
Eric Laurentcd772d02013-10-30 18:31:07 -07004393 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0,
4394 mStreamStates[AudioSystem.STREAM_MUSIC], 0);
4395 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
4396 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0,
4397 mStreamStates[AudioSystem.STREAM_RING], 0);
John Du5a0cf7a2013-07-19 11:30:34 -07004398 }
4399 }
4400
Paul McLean10804eb2015-01-28 11:16:35 -08004401 private boolean handleDeviceConnection(boolean connect, int device, String address, String deviceName) {
4402 Slog.i(TAG, "handleDeviceConnection(" + connect +
4403 " dev:" + Integer.toHexString(device) +
RoboErik5452e252015-02-06 15:33:53 -08004404 " address:" + address +
Paul McLean10804eb2015-01-28 11:16:35 -08004405 " name:" + deviceName + ")");
Eric Laurent59f48272012-04-05 19:42:21 -07004406 synchronized (mConnectedDevices) {
4407 boolean isConnected = (mConnectedDevices.containsKey(device) &&
Paul McLean10804eb2015-01-28 11:16:35 -08004408 (address.isEmpty() || mConnectedDevices.get(device).equals(address)));
Eric Laurent59f48272012-04-05 19:42:21 -07004409
Paul McLean10804eb2015-01-28 11:16:35 -08004410 if (isConnected && !connect) {
Eric Laurent59f48272012-04-05 19:42:21 -07004411 AudioSystem.setDeviceConnectionState(device,
4412 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004413 address, deviceName);
Eric Laurent59f48272012-04-05 19:42:21 -07004414 mConnectedDevices.remove(device);
4415 return true;
Paul McLean10804eb2015-01-28 11:16:35 -08004416 } else if (!isConnected && connect) {
Eric Laurent59f48272012-04-05 19:42:21 -07004417 AudioSystem.setDeviceConnectionState(device,
4418 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004419 address, deviceName);
4420 mConnectedDevices.put(new Integer(device), address);
Eric Laurent59f48272012-04-05 19:42:21 -07004421 return true;
4422 }
4423 }
4424 return false;
4425 }
4426
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004427 // Devices which removal triggers intent ACTION_AUDIO_BECOMING_NOISY. The intent is only
4428 // sent if none of these devices is connected.
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004429 // Access synchronized on mConnectedDevices
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004430 int mBecomingNoisyIntentDevices =
4431 AudioSystem.DEVICE_OUT_WIRED_HEADSET | AudioSystem.DEVICE_OUT_WIRED_HEADPHONE |
Eric Laurent948d3272014-05-16 15:18:45 -07004432 AudioSystem.DEVICE_OUT_ALL_A2DP | AudioSystem.DEVICE_OUT_HDMI |
Eric Laurent794da7a2012-08-30 11:30:16 -07004433 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET | AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET |
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004434 AudioSystem.DEVICE_OUT_ALL_USB | AudioSystem.DEVICE_OUT_LINE;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004435
4436 // must be called before removing the device from mConnectedDevices
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004437 // Called synchronized on mConnectedDevices
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004438 private int checkSendBecomingNoisyIntent(int device, int state) {
4439 int delay = 0;
4440 if ((state == 0) && ((device & mBecomingNoisyIntentDevices) != 0)) {
4441 int devices = 0;
4442 for (int dev : mConnectedDevices.keySet()) {
Eric Laurent27c30e42014-08-27 12:36:33 -07004443 if (((dev & AudioSystem.DEVICE_BIT_IN) == 0) &&
4444 ((dev & mBecomingNoisyIntentDevices) != 0)) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004445 devices |= dev;
4446 }
4447 }
4448 if (devices == device) {
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004449 sendMsg(mAudioHandler,
4450 MSG_BROADCAST_AUDIO_BECOMING_NOISY,
4451 SENDMSG_REPLACE,
4452 0,
4453 0,
4454 null,
4455 0);
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004456 delay = 1000;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004457 }
4458 }
4459
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004460 if (mAudioHandler.hasMessages(MSG_SET_A2DP_SRC_CONNECTION_STATE) ||
4461 mAudioHandler.hasMessages(MSG_SET_A2DP_SINK_CONNECTION_STATE) ||
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004462 mAudioHandler.hasMessages(MSG_SET_WIRED_DEVICE_CONNECTION_STATE)) {
Eric Laurentadbe8bf2014-11-03 18:26:32 -08004463 synchronized (mLastDeviceConnectMsgTime) {
4464 long time = SystemClock.uptimeMillis();
4465 if (mLastDeviceConnectMsgTime > time) {
Matthew Xiec525cf72015-01-22 20:13:17 -08004466 delay = (int)(mLastDeviceConnectMsgTime - time) + 30;
Eric Laurentadbe8bf2014-11-03 18:26:32 -08004467 }
4468 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004469 }
4470 return delay;
4471 }
4472
Paul McLean10804eb2015-01-28 11:16:35 -08004473 private void sendDeviceConnectionIntent(int device, int state, String address, String deviceName)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004474 {
Paul McLean10804eb2015-01-28 11:16:35 -08004475 Slog.i(TAG, "sendDeviceConnectionIntent(dev:0x" + Integer.toHexString(device) +
4476 " state:0x" + Integer.toHexString(state) +
4477 " address:" + address +
4478 " name:" + deviceName + ");");
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004479 Intent intent = new Intent();
4480
Paul McLean10804eb2015-01-28 11:16:35 -08004481 intent.putExtra(CONNECT_INTENT_KEY_STATE, state);
4482 intent.putExtra(CONNECT_INTENT_KEY_ADDRESS, address);
4483 intent.putExtra(CONNECT_INTENT_KEY_PORT_NAME, deviceName);
4484
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004485 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4486
Dianne Hackborn632ca412012-06-14 19:34:10 -07004487 int connType = 0;
4488
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004489 if (device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) {
Dianne Hackborn632ca412012-06-14 19:34:10 -07004490 connType = AudioRoutesInfo.MAIN_HEADSET;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004491 intent.setAction(Intent.ACTION_HEADSET_PLUG);
4492 intent.putExtra("microphone", 1);
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004493 } else if (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE ||
4494 device == AudioSystem.DEVICE_OUT_LINE) {
4495 /*do apps care about line-out vs headphones?*/
Dianne Hackborn632ca412012-06-14 19:34:10 -07004496 connType = AudioRoutesInfo.MAIN_HEADPHONES;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004497 intent.setAction(Intent.ACTION_HEADSET_PLUG);
4498 intent.putExtra("microphone", 0);
Eric Laurent6fa42452015-01-09 15:09:40 -08004499 } else if (device == AudioSystem.DEVICE_OUT_HDMI ||
4500 device == AudioSystem.DEVICE_OUT_HDMI_ARC) {
Dianne Hackborn632ca412012-06-14 19:34:10 -07004501 connType = AudioRoutesInfo.MAIN_HDMI;
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004502 configureHdmiPlugIntent(intent, state);
Paul McLean10804eb2015-01-28 11:16:35 -08004503 } else if (device == AudioSystem.DEVICE_OUT_USB_DEVICE) {
4504 connType = AudioRoutesInfo.MAIN_USB;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004505 }
4506
Dianne Hackborn632ca412012-06-14 19:34:10 -07004507 synchronized (mCurAudioRoutes) {
4508 if (connType != 0) {
John Spurlock61560172015-02-06 19:46:04 -05004509 int newConn = mCurAudioRoutes.mainType;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004510 if (state != 0) {
4511 newConn |= connType;
4512 } else {
4513 newConn &= ~connType;
4514 }
John Spurlock61560172015-02-06 19:46:04 -05004515 if (newConn != mCurAudioRoutes.mainType) {
4516 mCurAudioRoutes.mainType = newConn;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004517 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4518 SENDMSG_NOOP, 0, 0, null, 0);
4519 }
4520 }
4521 }
4522
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004523 final long ident = Binder.clearCallingIdentity();
4524 try {
4525 ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
4526 } finally {
4527 Binder.restoreCallingIdentity(ident);
4528 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004529 }
4530
Paul McLean10804eb2015-01-28 11:16:35 -08004531 private void onSetWiredDeviceConnectionState(int device, int state, String address,
4532 String deviceName)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004533 {
Paul McLean10804eb2015-01-28 11:16:35 -08004534 Slog.i(TAG, "onSetWiredDeviceConnectionState(dev:" + Integer.toHexString(device)
4535 + " state:" + Integer.toHexString(state)
4536 + " address:" + address
4537 + " deviceName:" + deviceName + ");");
4538
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004539 synchronized (mConnectedDevices) {
4540 if ((state == 0) && ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004541 (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) ||
4542 (device == AudioSystem.DEVICE_OUT_LINE))) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004543 setBluetoothA2dpOnInt(true);
4544 }
Eric Laurentae4506e2014-05-29 16:04:32 -07004545 boolean isUsb = ((device & ~AudioSystem.DEVICE_OUT_ALL_USB) == 0) ||
4546 (((device & AudioSystem.DEVICE_BIT_IN) != 0) &&
4547 ((device & ~AudioSystem.DEVICE_IN_ALL_USB) == 0));
Paul McLean10804eb2015-01-28 11:16:35 -08004548 handleDeviceConnection(state == 1, device, address, deviceName);
Eric Laurentf1a457d2012-09-20 16:27:23 -07004549 if (state != 0) {
4550 if ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004551 (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) ||
4552 (device == AudioSystem.DEVICE_OUT_LINE)) {
Eric Laurentf1a457d2012-09-20 16:27:23 -07004553 setBluetoothA2dpOnInt(false);
4554 }
4555 if ((device & mSafeMediaVolumeDevices) != 0) {
4556 sendMsg(mAudioHandler,
4557 MSG_CHECK_MUSIC_ACTIVE,
4558 SENDMSG_REPLACE,
4559 0,
4560 0,
4561 null,
4562 MUSIC_ACTIVE_POLL_PERIOD_MS);
4563 }
Eric Laurent212532b2014-07-21 15:43:18 -07004564 // Television devices without CEC service apply software volume on HDMI output
4565 if (isPlatformTelevision() && ((device & AudioSystem.DEVICE_OUT_HDMI) != 0)) {
4566 mFixedVolumeDevices |= AudioSystem.DEVICE_OUT_HDMI;
4567 checkAllFixedVolumeDevices();
4568 if (mHdmiManager != null) {
4569 synchronized (mHdmiManager) {
4570 if (mHdmiPlaybackClient != null) {
4571 mHdmiCecSink = false;
4572 mHdmiPlaybackClient.queryDisplayStatus(mHdmiDisplayStatusCallback);
4573 }
4574 }
4575 }
4576 }
4577 } else {
4578 if (isPlatformTelevision() && ((device & AudioSystem.DEVICE_OUT_HDMI) != 0)) {
4579 if (mHdmiManager != null) {
4580 synchronized (mHdmiManager) {
4581 mHdmiCecSink = false;
4582 }
4583 }
4584 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004585 }
Paul McLean10804eb2015-01-28 11:16:35 -08004586 if (!isUsb && device != AudioSystem.DEVICE_IN_WIRED_HEADSET) {
4587 sendDeviceConnectionIntent(device, state, address, deviceName);
Mike Lockwooddb454842012-09-18 11:16:57 -07004588 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004589 }
4590 }
4591
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004592 private void configureHdmiPlugIntent(Intent intent, int state) {
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004593 intent.setAction(AudioManager.ACTION_HDMI_AUDIO_PLUG);
4594 intent.putExtra(AudioManager.EXTRA_AUDIO_PLUG_STATE, state);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004595 if (state == 1) {
4596 ArrayList<AudioPort> ports = new ArrayList<AudioPort>();
4597 int[] portGeneration = new int[1];
4598 int status = AudioSystem.listAudioPorts(ports, portGeneration);
4599 if (status == AudioManager.SUCCESS) {
4600 for (AudioPort port : ports) {
4601 if (port instanceof AudioDevicePort) {
4602 final AudioDevicePort devicePort = (AudioDevicePort) port;
Eric Laurent6fa42452015-01-09 15:09:40 -08004603 if (devicePort.type() == AudioManager.DEVICE_OUT_HDMI ||
4604 devicePort.type() == AudioManager.DEVICE_OUT_HDMI_ARC) {
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004605 // format the list of supported encodings
4606 int[] formats = devicePort.formats();
4607 if (formats.length > 0) {
4608 ArrayList<Integer> encodingList = new ArrayList(1);
4609 for (int format : formats) {
4610 // a format in the list can be 0, skip it
4611 if (format != AudioFormat.ENCODING_INVALID) {
4612 encodingList.add(format);
4613 }
4614 }
4615 int[] encodingArray = new int[encodingList.size()];
4616 for (int i = 0 ; i < encodingArray.length ; i++) {
4617 encodingArray[i] = encodingList.get(i);
4618 }
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004619 intent.putExtra(AudioManager.EXTRA_ENCODINGS, encodingArray);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004620 }
4621 // find the maximum supported number of channels
4622 int maxChannels = 0;
4623 for (int mask : devicePort.channelMasks()) {
4624 int channelCount = AudioFormat.channelCountFromOutChannelMask(mask);
4625 if (channelCount > maxChannels) {
4626 maxChannels = channelCount;
4627 }
4628 }
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004629 intent.putExtra(AudioManager.EXTRA_MAX_CHANNEL_COUNT, maxChannels);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004630 }
4631 }
4632 }
4633 }
4634 }
4635 }
4636
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004637 /* cache of the address of the last dock the device was connected to */
4638 private String mDockAddress;
4639
Eric Laurenta553c252009-07-17 12:17:14 -07004640 /**
4641 * Receiver for misc intent broadcasts the Phone app cares about.
4642 */
4643 private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
4644 @Override
4645 public void onReceive(Context context, Intent intent) {
4646 String action = intent.getAction();
Eric Laurentae4506e2014-05-29 16:04:32 -07004647 int outDevice;
4648 int inDevice;
Eric Laurent59f48272012-04-05 19:42:21 -07004649 int state;
Eric Laurenta553c252009-07-17 12:17:14 -07004650
Jean-Michel Trivi758559e2010-03-09 09:26:08 -08004651 if (action.equals(Intent.ACTION_DOCK_EVENT)) {
4652 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4653 Intent.EXTRA_DOCK_STATE_UNDOCKED);
4654 int config;
4655 switch (dockState) {
4656 case Intent.EXTRA_DOCK_STATE_DESK:
4657 config = AudioSystem.FORCE_BT_DESK_DOCK;
4658 break;
4659 case Intent.EXTRA_DOCK_STATE_CAR:
4660 config = AudioSystem.FORCE_BT_CAR_DOCK;
4661 break;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05004662 case Intent.EXTRA_DOCK_STATE_LE_DESK:
Eric Laurent08ed1b92012-11-05 14:54:12 -08004663 config = AudioSystem.FORCE_ANALOG_DOCK;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05004664 break;
4665 case Intent.EXTRA_DOCK_STATE_HE_DESK:
4666 config = AudioSystem.FORCE_DIGITAL_DOCK;
4667 break;
Jean-Michel Trivi758559e2010-03-09 09:26:08 -08004668 case Intent.EXTRA_DOCK_STATE_UNDOCKED:
4669 default:
4670 config = AudioSystem.FORCE_NONE;
4671 }
Eric Laurent08ed1b92012-11-05 14:54:12 -08004672 // Low end docks have a menu to enable or disable audio
4673 // (see mDockAudioMediaEnabled)
4674 if (!((dockState == Intent.EXTRA_DOCK_STATE_LE_DESK) ||
4675 ((dockState == Intent.EXTRA_DOCK_STATE_UNDOCKED) &&
4676 (mDockState == Intent.EXTRA_DOCK_STATE_LE_DESK)))) {
4677 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
4678 }
4679 mDockState = dockState;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07004680 } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
Eric Laurent59f48272012-04-05 19:42:21 -07004681 state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07004682 BluetoothProfile.STATE_DISCONNECTED);
Eric Laurentae4506e2014-05-29 16:04:32 -07004683 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
4684 inDevice = AudioSystem.DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Nick Pellya56d1c72009-08-19 14:49:29 -07004685 String address = null;
Eric Laurentdca56b92011-09-02 14:20:56 -07004686
4687 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
4688 if (btDevice == null) {
4689 return;
4690 }
4691
4692 address = btDevice.getAddress();
4693 BluetoothClass btClass = btDevice.getBluetoothClass();
4694 if (btClass != null) {
4695 switch (btClass.getDeviceClass()) {
4696 case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
4697 case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
Eric Laurentae4506e2014-05-29 16:04:32 -07004698 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurentdca56b92011-09-02 14:20:56 -07004699 break;
4700 case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
Eric Laurentae4506e2014-05-29 16:04:32 -07004701 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurentdca56b92011-09-02 14:20:56 -07004702 break;
Eric Laurentd5603c12009-08-06 08:49:39 -07004703 }
4704 }
4705
Eric Laurentdca56b92011-09-02 14:20:56 -07004706 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4707 address = "";
4708 }
Eric Laurentd5603c12009-08-06 08:49:39 -07004709
Eric Laurent59f48272012-04-05 19:42:21 -07004710 boolean connected = (state == BluetoothProfile.STATE_CONNECTED);
Paul McLean10804eb2015-01-28 11:16:35 -08004711 boolean success =
4712 handleDeviceConnection(connected, outDevice, address, "Bluetooth Headset") &&
4713 handleDeviceConnection(connected, inDevice, address, "Bluetooth Headset");
Eric Laurentae4506e2014-05-29 16:04:32 -07004714 if (success) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004715 synchronized (mScoClients) {
Eric Laurent59f48272012-04-05 19:42:21 -07004716 if (connected) {
4717 mBluetoothHeadsetDevice = btDevice;
4718 } else {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004719 mBluetoothHeadsetDevice = null;
4720 resetBluetoothSco();
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004721 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004722 }
Eric Laurenta553c252009-07-17 12:17:14 -07004723 }
Paul McLeandf361462014-04-10 16:02:55 -07004724 } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004725 boolean broadcast = false;
Eric Laurent59f48272012-04-05 19:42:21 -07004726 int scoAudioState = AudioManager.SCO_AUDIO_STATE_ERROR;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004727 synchronized (mScoClients) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004728 int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
Eric Laurentdc03c612011-04-01 10:59:41 -07004729 // broadcast intent if the connection was initated by AudioService
4730 if (!mScoClients.isEmpty() &&
4731 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
4732 mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
4733 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004734 broadcast = true;
4735 }
4736 switch (btState) {
4737 case BluetoothHeadset.STATE_AUDIO_CONNECTED:
Eric Laurent59f48272012-04-05 19:42:21 -07004738 scoAudioState = AudioManager.SCO_AUDIO_STATE_CONNECTED;
Eric Laurentdc03c612011-04-01 10:59:41 -07004739 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
4740 mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
4741 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004742 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004743 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004744 break;
4745 case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
Eric Laurent59f48272012-04-05 19:42:21 -07004746 scoAudioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
Eric Laurent62ef7672010-11-24 10:58:32 -08004747 mScoAudioState = SCO_STATE_INACTIVE;
Eric Laurentd7454be2011-09-14 08:45:58 -07004748 clearAllScoClients(0, false);
Eric Laurent62ef7672010-11-24 10:58:32 -08004749 break;
4750 case BluetoothHeadset.STATE_AUDIO_CONNECTING:
Eric Laurentdc03c612011-04-01 10:59:41 -07004751 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
4752 mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
4753 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004754 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004755 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004756 default:
4757 // do not broadcast CONNECTING or invalid state
4758 broadcast = false;
4759 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004760 }
4761 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004762 if (broadcast) {
Eric Laurent59f48272012-04-05 19:42:21 -07004763 broadcastScoConnectionState(scoAudioState);
Eric Laurentdc03c612011-04-01 10:59:41 -07004764 //FIXME: this is to maintain compatibility with deprecated intent
4765 // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Eric Laurent62ef7672010-11-24 10:58:32 -08004766 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
Eric Laurent59f48272012-04-05 19:42:21 -07004767 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, scoAudioState);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004768 sendStickyBroadcastToAll(newIntent);
Eric Laurent62ef7672010-11-24 10:58:32 -08004769 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004770 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
Jon Eklund318f0fe2014-01-23 17:53:48 -06004771 if (mMonitorRotation) {
4772 mOrientationListener.onOrientationChanged(0); //argument is ignored anyway
4773 mOrientationListener.enable();
4774 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004775 AudioSystem.setParameters("screen_state=on");
4776 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Jon Eklund318f0fe2014-01-23 17:53:48 -06004777 if (mMonitorRotation) {
4778 //reduce wakeups (save current) by only listening when display is on
4779 mOrientationListener.disable();
4780 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004781 AudioSystem.setParameters("screen_state=off");
Dianne Hackborn961cae92013-03-20 14:59:43 -07004782 } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004783 handleConfigurationChanged(context);
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004784 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004785 // attempt to stop music playback for background user
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004786 sendMsg(mAudioHandler,
4787 MSG_BROADCAST_AUDIO_BECOMING_NOISY,
4788 SENDMSG_REPLACE,
4789 0,
4790 0,
4791 null,
4792 0);
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004793 // the current audio focus owner is no longer valid
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004794 mMediaFocusControl.discardAudioFocusOwner();
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004795
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004796 // load volume settings for new user
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004797 readAudioSettings(true /*userSwitch*/);
4798 // preserve STREAM_MUSIC volume from one user to the next.
4799 sendMsg(mAudioHandler,
4800 MSG_SET_ALL_VOLUMES,
4801 SENDMSG_QUEUE,
4802 0,
4803 0,
4804 mStreamStates[AudioSystem.STREAM_MUSIC], 0);
Eric Laurenta553c252009-07-17 12:17:14 -07004805 }
4806 }
Paul McLeanc837a452014-04-09 09:04:43 -07004807 } // end class AudioServiceBroadcastReceiver
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08004808
4809 //==========================================================================================
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004810 // RemoteControlDisplay / RemoteControlClient / Remote info
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08004811 //==========================================================================================
Jean-Michel Trivif108cdd92013-09-27 18:37:36 -07004812 public boolean registerRemoteController(IRemoteControlDisplay rcd, int w, int h,
4813 ComponentName listenerComp) {
4814 return mMediaFocusControl.registerRemoteController(rcd, w, h, listenerComp);
4815 }
4816
Jean-Michel Trivi7ddd2262013-09-01 18:06:45 -07004817 public boolean registerRemoteControlDisplay(IRemoteControlDisplay rcd, int w, int h) {
Jean-Michel Trivif108cdd92013-09-27 18:37:36 -07004818 return mMediaFocusControl.registerRemoteControlDisplay(rcd, w, h);
Jean-Michel Trivi8f619182011-07-21 15:10:10 -07004819 }
Jean-Michel Trivid327f212010-03-16 21:44:33 -07004820
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07004821 public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004822 mMediaFocusControl.unregisterRemoteControlDisplay(rcd);
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07004823 }
4824
4825 public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004826 mMediaFocusControl.remoteControlDisplayUsesBitmapSize(rcd, w, h);
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07004827 }
4828
Jean-Michel Trivic3c4bab2013-04-19 08:56:50 -07004829 public void remoteControlDisplayWantsPlaybackPositionSync(IRemoteControlDisplay rcd,
4830 boolean wantsSync) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004831 mMediaFocusControl.remoteControlDisplayWantsPlaybackPositionSync(rcd, wantsSync);
4832 }
4833
John Spurlock3346a802014-05-20 16:25:37 -04004834 @Override
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004835 public void setRemoteStreamVolume(int index) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05004836 enforceVolumeController("set the remote stream volume");
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004837 mMediaFocusControl.setRemoteStreamVolume(index);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07004838 }
4839
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004840 //==========================================================================================
4841 // Audio Focus
4842 //==========================================================================================
Jean-Michel Trivifd6ad742014-11-10 14:38:30 -08004843 public int requestAudioFocus(AudioAttributes aa, int durationHint, IBinder cb,
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08004844 IAudioFocusDispatcher fd, String clientId, String callingPackageName, int flags,
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08004845 IAudioPolicyCallback pcb) {
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08004846 // permission checks
4847 if ((flags & AudioManager.AUDIOFOCUS_FLAG_LOCK) == AudioManager.AUDIOFOCUS_FLAG_LOCK) {
John Spurlock61560172015-02-06 19:46:04 -05004848 if (AudioSystem.IN_VOICE_COMM_FOCUS_ID.equals(clientId)) {
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08004849 if (PackageManager.PERMISSION_GRANTED != mContext.checkCallingOrSelfPermission(
4850 android.Manifest.permission.MODIFY_PHONE_STATE)) {
4851 Log.e(TAG, "Invalid permission to (un)lock audio focus", new Exception());
4852 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
4853 }
4854 } else {
4855 // only a registered audio policy can be used to lock focus
4856 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08004857 if (!mAudioPolicies.containsKey(pcb.asBinder())) {
4858 Log.e(TAG, "Invalid unregistered AudioPolicy to (un)lock audio focus");
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08004859 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
4860 }
4861 }
4862 }
4863 }
4864
Jean-Michel Trivifd6ad742014-11-10 14:38:30 -08004865 return mMediaFocusControl.requestAudioFocus(aa, durationHint, cb, fd,
4866 clientId, callingPackageName, flags);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004867 }
4868
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08004869 public int abandonAudioFocus(IAudioFocusDispatcher fd, String clientId, AudioAttributes aa) {
4870 return mMediaFocusControl.abandonAudioFocus(fd, clientId, aa);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004871 }
4872
4873 public void unregisterAudioFocusClient(String clientId) {
4874 mMediaFocusControl.unregisterAudioFocusClient(clientId);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07004875 }
4876
Jean-Michel Trivi23805662013-07-31 14:19:18 -07004877 public int getCurrentAudioFocus() {
4878 return mMediaFocusControl.getCurrentAudioFocus();
4879 }
4880
John Spurlock5e783732015-02-19 10:28:59 -05004881 private boolean readCameraSoundForced() {
4882 return SystemProperties.getBoolean("audio.camerasound.force", false) ||
4883 mContext.getResources().getBoolean(
4884 com.android.internal.R.bool.config_camera_sound_forced);
4885 }
4886
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004887 //==========================================================================================
4888 // Device orientation
4889 //==========================================================================================
4890 /**
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07004891 * Handles device configuration changes that may map to a change in the orientation
4892 * or orientation.
4893 * Monitoring orientation and rotation is optional, and is defined by the definition and value
4894 * of the "ro.audio.monitorOrientation" and "ro.audio.monitorRotation" system properties.
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004895 */
4896 private void handleConfigurationChanged(Context context) {
4897 try {
4898 // reading new orientation "safely" (i.e. under try catch) in case anything
4899 // goes wrong when obtaining resources and configuration
Eric Laurentd640bd32012-09-28 18:01:48 -07004900 Configuration config = context.getResources().getConfiguration();
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07004901 // TODO merge rotation and orientation
Eric Laurentd640bd32012-09-28 18:01:48 -07004902 if (mMonitorOrientation) {
4903 int newOrientation = config.orientation;
4904 if (newOrientation != mDeviceOrientation) {
4905 mDeviceOrientation = newOrientation;
4906 setOrientationForAudioSystem();
4907 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004908 }
Eric Laurentd640bd32012-09-28 18:01:48 -07004909 sendMsg(mAudioHandler,
4910 MSG_CONFIGURE_SAFE_MEDIA_VOLUME,
4911 SENDMSG_REPLACE,
4912 0,
4913 0,
4914 null,
4915 0);
Eric Laurentdd45d012012-10-08 09:04:34 -07004916
John Spurlock5e783732015-02-19 10:28:59 -05004917 boolean cameraSoundForced = readCameraSoundForced();
Eric Laurentdd45d012012-10-08 09:04:34 -07004918 synchronized (mSettingsLock) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07004919 boolean cameraSoundForcedChanged = false;
Eric Laurentdd45d012012-10-08 09:04:34 -07004920 synchronized (mCameraSoundForced) {
4921 if (cameraSoundForced != mCameraSoundForced) {
4922 mCameraSoundForced = cameraSoundForced;
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07004923 cameraSoundForcedChanged = true;
Eric Laurentdd45d012012-10-08 09:04:34 -07004924 }
4925 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07004926 if (cameraSoundForcedChanged) {
4927 if (!isPlatformTelevision()) {
4928 VolumeStreamState s = mStreamStates[AudioSystem.STREAM_SYSTEM_ENFORCED];
4929 if (cameraSoundForced) {
4930 s.setAllIndexesToMax();
4931 mRingerModeAffectedStreams &=
4932 ~(1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
4933 } else {
4934 s.setAllIndexes(mStreamStates[AudioSystem.STREAM_SYSTEM]);
4935 mRingerModeAffectedStreams |=
4936 (1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
4937 }
4938 // take new state into account for streams muted by ringer mode
John Spurlock661f2cf2014-11-17 10:29:10 -05004939 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07004940 }
4941
4942 sendMsg(mAudioHandler,
4943 MSG_SET_FORCE_USE,
4944 SENDMSG_QUEUE,
4945 AudioSystem.FOR_SYSTEM,
4946 cameraSoundForced ?
4947 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE,
4948 null,
4949 0);
4950
4951 sendMsg(mAudioHandler,
4952 MSG_SET_ALL_VOLUMES,
4953 SENDMSG_QUEUE,
4954 0,
4955 0,
4956 mStreamStates[AudioSystem.STREAM_SYSTEM_ENFORCED], 0);
4957 }
Eric Laurentdd45d012012-10-08 09:04:34 -07004958 }
John Spurlock3346a802014-05-20 16:25:37 -04004959 mVolumeController.setLayoutDirection(config.getLayoutDirection());
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004960 } catch (Exception e) {
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07004961 Log.e(TAG, "Error handling configuration change: ", e);
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004962 }
4963 }
4964
4965 private void setOrientationForAudioSystem() {
4966 switch (mDeviceOrientation) {
4967 case Configuration.ORIENTATION_LANDSCAPE:
4968 //Log.i(TAG, "orientation is landscape");
4969 AudioSystem.setParameters("orientation=landscape");
4970 break;
4971 case Configuration.ORIENTATION_PORTRAIT:
4972 //Log.i(TAG, "orientation is portrait");
4973 AudioSystem.setParameters("orientation=portrait");
4974 break;
4975 case Configuration.ORIENTATION_SQUARE:
4976 //Log.i(TAG, "orientation is square");
4977 AudioSystem.setParameters("orientation=square");
4978 break;
4979 case Configuration.ORIENTATION_UNDEFINED:
4980 //Log.i(TAG, "orientation is undefined");
4981 AudioSystem.setParameters("orientation=undefined");
4982 break;
4983 default:
4984 Log.e(TAG, "Unknown orientation");
4985 }
4986 }
4987
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07004988 private void setRotationForAudioSystem() {
4989 switch (mDeviceRotation) {
4990 case Surface.ROTATION_0:
4991 AudioSystem.setParameters("rotation=0");
4992 break;
4993 case Surface.ROTATION_90:
4994 AudioSystem.setParameters("rotation=90");
4995 break;
4996 case Surface.ROTATION_180:
4997 AudioSystem.setParameters("rotation=180");
4998 break;
4999 case Surface.ROTATION_270:
5000 AudioSystem.setParameters("rotation=270");
5001 break;
5002 default:
5003 Log.e(TAG, "Unknown device rotation");
5004 }
5005 }
5006
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005007
Eric Laurent78472112012-05-21 08:57:21 -07005008 // Handles request to override default use of A2DP for media.
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005009 // Must be called synchronized on mConnectedDevices
Eric Laurent78472112012-05-21 08:57:21 -07005010 public void setBluetoothA2dpOnInt(boolean on) {
5011 synchronized (mBluetoothA2dpEnabledLock) {
5012 mBluetoothA2dpEnabled = on;
Eric Laurentc390bed2012-07-03 12:24:05 -07005013 mAudioHandler.removeMessages(MSG_SET_FORCE_BT_A2DP_USE);
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005014 setForceUseInt_SyncDevices(AudioSystem.FOR_MEDIA,
Eric Laurentc390bed2012-07-03 12:24:05 -07005015 mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP);
Eric Laurent78472112012-05-21 08:57:21 -07005016 }
5017 }
5018
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005019 // Must be called synchronized on mConnectedDevices
5020 private void setForceUseInt_SyncDevices(int usage, int config) {
5021 switch (usage) {
5022 case AudioSystem.FOR_MEDIA:
5023 if (config == AudioSystem.FORCE_NO_BT_A2DP) {
5024 mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ALL_A2DP;
5025 } else { // config == AudioSystem.FORCE_NONE
5026 mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ALL_A2DP;
5027 }
5028 break;
5029 case AudioSystem.FOR_DOCK:
5030 if (config == AudioSystem.FORCE_ANALOG_DOCK) {
5031 mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
5032 } else { // config == AudioSystem.FORCE_NONE
5033 mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
5034 }
5035 break;
5036 default:
5037 // usage doesn't affect the broadcast of ACTION_AUDIO_BECOMING_NOISY
5038 }
5039 AudioSystem.setForceUse(usage, config);
5040 }
5041
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005042 @Override
Jeff Sharkey098d5802012-04-26 17:30:34 -07005043 public void setRingtonePlayer(IRingtonePlayer player) {
5044 mContext.enforceCallingOrSelfPermission(REMOTE_AUDIO_PLAYBACK, null);
5045 mRingtonePlayer = player;
5046 }
5047
5048 @Override
5049 public IRingtonePlayer getRingtonePlayer() {
5050 return mRingtonePlayer;
5051 }
5052
5053 @Override
Dianne Hackborn632ca412012-06-14 19:34:10 -07005054 public AudioRoutesInfo startWatchingRoutes(IAudioRoutesObserver observer) {
5055 synchronized (mCurAudioRoutes) {
5056 AudioRoutesInfo routes = new AudioRoutesInfo(mCurAudioRoutes);
5057 mRoutesObservers.register(observer);
5058 return routes;
5059 }
5060 }
5061
Eric Laurentc34dcc12012-09-10 13:51:52 -07005062
5063 //==========================================================================================
5064 // Safe media volume management.
5065 // MUSIC stream volume level is limited when headphones are connected according to safety
5066 // regulation. When the user attempts to raise the volume above the limit, a warning is
5067 // displayed and the user has to acknowlegde before the volume is actually changed.
5068 // The volume index corresponding to the limit is stored in config_safe_media_volume_index
5069 // property. Platforms with a different limit must set this property accordingly in their
5070 // overlay.
5071 //==========================================================================================
5072
Eric Laurentd640bd32012-09-28 18:01:48 -07005073 // mSafeMediaVolumeState indicates whether the media volume is limited over headphones.
5074 // It is SAFE_MEDIA_VOLUME_NOT_CONFIGURED at boot time until a network service is connected
5075 // or the configure time is elapsed. It is then set to SAFE_MEDIA_VOLUME_ACTIVE or
5076 // SAFE_MEDIA_VOLUME_DISABLED according to country option. If not SAFE_MEDIA_VOLUME_DISABLED, it
5077 // can be set to SAFE_MEDIA_VOLUME_INACTIVE by calling AudioService.disableSafeMediaVolume()
5078 // (when user opts out).
John Spurlock35134602014-07-24 18:10:48 -04005079 private static final int SAFE_MEDIA_VOLUME_NOT_CONFIGURED = 0;
5080 private static final int SAFE_MEDIA_VOLUME_DISABLED = 1;
5081 private static final int SAFE_MEDIA_VOLUME_INACTIVE = 2; // confirmed
5082 private static final int SAFE_MEDIA_VOLUME_ACTIVE = 3; // unconfirmed
Eric Laurentd640bd32012-09-28 18:01:48 -07005083 private Integer mSafeMediaVolumeState;
5084
5085 private int mMcc = 0;
Eric Laurentc34dcc12012-09-10 13:51:52 -07005086 // mSafeMediaVolumeIndex is the cached value of config_safe_media_volume_index property
Eric Laurentd640bd32012-09-28 18:01:48 -07005087 private int mSafeMediaVolumeIndex;
Eric Laurentc34dcc12012-09-10 13:51:52 -07005088 // mSafeMediaVolumeDevices lists the devices for which safe media volume is enforced,
5089 private final int mSafeMediaVolumeDevices = AudioSystem.DEVICE_OUT_WIRED_HEADSET |
5090 AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
5091 // mMusicActiveMs is the cumulative time of music activity since safe volume was disabled.
5092 // When this time reaches UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX, the safe media volume is re-enabled
5093 // automatically. mMusicActiveMs is rounded to a multiple of MUSIC_ACTIVE_POLL_PERIOD_MS.
5094 private int mMusicActiveMs;
5095 private static final int UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX = (20 * 3600 * 1000); // 20 hours
5096 private static final int MUSIC_ACTIVE_POLL_PERIOD_MS = 60000; // 1 minute polling interval
Eric Laurentd640bd32012-09-28 18:01:48 -07005097 private static final int SAFE_VOLUME_CONFIGURE_TIMEOUT_MS = 30000; // 30s after boot completed
Eric Laurentc34dcc12012-09-10 13:51:52 -07005098
5099 private void setSafeMediaVolumeEnabled(boolean on) {
Eric Laurentd640bd32012-09-28 18:01:48 -07005100 synchronized (mSafeMediaVolumeState) {
5101 if ((mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_NOT_CONFIGURED) &&
5102 (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_DISABLED)) {
5103 if (on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE)) {
5104 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE;
5105 enforceSafeMediaVolume();
5106 } else if (!on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE)) {
5107 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE;
John Spurlockaa5ee4d2014-07-25 13:05:12 -04005108 mMusicActiveMs = 1; // nonzero = confirmed
5109 saveMusicActiveMs();
Eric Laurentd640bd32012-09-28 18:01:48 -07005110 sendMsg(mAudioHandler,
5111 MSG_CHECK_MUSIC_ACTIVE,
5112 SENDMSG_REPLACE,
5113 0,
5114 0,
5115 null,
5116 MUSIC_ACTIVE_POLL_PERIOD_MS);
5117 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005118 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005119 }
5120 }
5121
5122 private void enforceSafeMediaVolume() {
5123 VolumeStreamState streamState = mStreamStates[AudioSystem.STREAM_MUSIC];
Eric Laurentc34dcc12012-09-10 13:51:52 -07005124 int devices = mSafeMediaVolumeDevices;
5125 int i = 0;
5126
5127 while (devices != 0) {
5128 int device = 1 << i++;
5129 if ((device & devices) == 0) {
5130 continue;
5131 }
Eric Laurent42b041e2013-03-29 11:36:03 -07005132 int index = streamState.getIndex(device);
Eric Laurentc34dcc12012-09-10 13:51:52 -07005133 if (index > mSafeMediaVolumeIndex) {
Eric Laurent42b041e2013-03-29 11:36:03 -07005134 streamState.setIndex(mSafeMediaVolumeIndex, device);
5135 sendMsg(mAudioHandler,
5136 MSG_SET_DEVICE_VOLUME,
5137 SENDMSG_QUEUE,
5138 device,
5139 0,
5140 streamState,
5141 0);
Eric Laurentc34dcc12012-09-10 13:51:52 -07005142 }
5143 devices &= ~device;
5144 }
5145 }
5146
5147 private boolean checkSafeMediaVolume(int streamType, int index, int device) {
Eric Laurentd640bd32012-09-28 18:01:48 -07005148 synchronized (mSafeMediaVolumeState) {
5149 if ((mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) &&
Eric Laurentc34dcc12012-09-10 13:51:52 -07005150 (mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) &&
5151 ((device & mSafeMediaVolumeDevices) != 0) &&
5152 (index > mSafeMediaVolumeIndex)) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07005153 return false;
5154 }
5155 return true;
5156 }
5157 }
5158
John Spurlock3346a802014-05-20 16:25:37 -04005159 @Override
Eric Laurentc34dcc12012-09-10 13:51:52 -07005160 public void disableSafeMediaVolume() {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005161 enforceVolumeController("disable the safe media volume");
Eric Laurentd640bd32012-09-28 18:01:48 -07005162 synchronized (mSafeMediaVolumeState) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07005163 setSafeMediaVolumeEnabled(false);
Eric Laurentfde16d52012-12-03 14:42:39 -08005164 if (mPendingVolumeCommand != null) {
5165 onSetStreamVolume(mPendingVolumeCommand.mStreamType,
5166 mPendingVolumeCommand.mIndex,
5167 mPendingVolumeCommand.mFlags,
5168 mPendingVolumeCommand.mDevice);
5169 mPendingVolumeCommand = null;
5170 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005171 }
5172 }
5173
Jungshik Jang41d97462014-06-30 22:26:29 +09005174 //==========================================================================================
5175 // Hdmi Cec system audio mode.
John Spurlockbc82b122015-03-02 16:12:38 -05005176 // If Hdmi Cec's system audio mode is on, audio service should send the volume change
5177 // to HdmiControlService so that the audio receiver can handle it.
Jungshik Jang41d97462014-06-30 22:26:29 +09005178 //==========================================================================================
5179
Eric Laurent212532b2014-07-21 15:43:18 -07005180 private class MyDisplayStatusCallback implements HdmiPlaybackClient.DisplayStatusCallback {
5181 public void onComplete(int status) {
5182 if (mHdmiManager != null) {
5183 synchronized (mHdmiManager) {
5184 mHdmiCecSink = (status != HdmiControlManager.POWER_STATUS_UNKNOWN);
5185 // Television devices without CEC service apply software volume on HDMI output
5186 if (isPlatformTelevision() && !mHdmiCecSink) {
5187 mFixedVolumeDevices &= ~AudioSystem.DEVICE_OUT_HDMI;
5188 }
5189 checkAllFixedVolumeDevices();
5190 }
5191 }
5192 }
5193 };
5194
Jungshik Jang41d97462014-06-30 22:26:29 +09005195 // If HDMI-CEC system audio is supported
5196 private boolean mHdmiSystemAudioSupported = false;
5197 // Set only when device is tv.
5198 private HdmiTvClient mHdmiTvClient;
Eric Laurent0b03f992014-11-18 18:08:02 -08005199 // true if the device has system feature PackageManager.FEATURE_LEANBACK.
Eric Laurent212532b2014-07-21 15:43:18 -07005200 // cached HdmiControlManager interface
5201 private HdmiControlManager mHdmiManager;
5202 // Set only when device is a set-top box.
5203 private HdmiPlaybackClient mHdmiPlaybackClient;
5204 // true if we are a set-top box, an HDMI sink is connected and it supports CEC.
5205 private boolean mHdmiCecSink;
5206
5207 private MyDisplayStatusCallback mHdmiDisplayStatusCallback = new MyDisplayStatusCallback();
Jungshik Jang41d97462014-06-30 22:26:29 +09005208
5209 @Override
Jungshik Jang12307ca2014-07-15 19:27:56 +09005210 public int setHdmiSystemAudioSupported(boolean on) {
Eric Laurent212532b2014-07-21 15:43:18 -07005211 int device = AudioSystem.DEVICE_NONE;
5212 if (mHdmiManager != null) {
5213 synchronized (mHdmiManager) {
5214 if (mHdmiTvClient == null) {
5215 Log.w(TAG, "Only Hdmi-Cec enabled TV device supports system audio mode.");
5216 return device;
5217 }
Jungshik Jang41d97462014-06-30 22:26:29 +09005218
Eric Laurent212532b2014-07-21 15:43:18 -07005219 synchronized (mHdmiTvClient) {
5220 if (mHdmiSystemAudioSupported != on) {
5221 mHdmiSystemAudioSupported = on;
5222 AudioSystem.setForceUse(AudioSystem.FOR_HDMI_SYSTEM_AUDIO,
5223 on ? AudioSystem.FORCE_HDMI_SYSTEM_AUDIO_ENFORCED :
5224 AudioSystem.FORCE_NONE);
5225 }
5226 device = AudioSystem.getDevicesForStream(AudioSystem.STREAM_MUSIC);
5227 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005228 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005229 }
Eric Laurent212532b2014-07-21 15:43:18 -07005230 return device;
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005231 }
Jungshik Jang41d97462014-06-30 22:26:29 +09005232
Terry Heoe7d6d972014-09-04 21:05:28 +09005233 @Override
5234 public boolean isHdmiSystemAudioSupported() {
5235 return mHdmiSystemAudioSupported;
5236 }
5237
Eric Laurentdd45d012012-10-08 09:04:34 -07005238 //==========================================================================================
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07005239 // Accessibility: taking touch exploration into account for selecting the default
5240 // stream override timeout when adjusting volume
5241 //==========================================================================================
5242 private static class StreamOverride
5243 implements AccessibilityManager.TouchExplorationStateChangeListener {
5244
5245 // AudioService.getActiveStreamType() will return:
5246 // - STREAM_NOTIFICATION on tablets during this period after a notification stopped
5247 // - STREAM_MUSIC on phones during this period after music or talkback/voice search prompt
5248 // stopped
5249 private static final int DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS = 5000;
5250 private static final int TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS = 1000;
5251
5252 static int sDelayMs;
5253
5254 static void init(Context ctxt) {
5255 AccessibilityManager accessibilityManager =
5256 (AccessibilityManager) ctxt.getSystemService(Context.ACCESSIBILITY_SERVICE);
5257 updateDefaultStreamOverrideDelay(
5258 accessibilityManager.isTouchExplorationEnabled());
5259 accessibilityManager.addTouchExplorationStateChangeListener(
5260 new StreamOverride());
5261 }
5262
5263 @Override
5264 public void onTouchExplorationStateChanged(boolean enabled) {
5265 updateDefaultStreamOverrideDelay(enabled);
5266 }
5267
5268 private static void updateDefaultStreamOverrideDelay(boolean touchExploreEnabled) {
5269 if (touchExploreEnabled) {
5270 sDelayMs = TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS;
5271 } else {
5272 sDelayMs = DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS;
5273 }
5274 if (DEBUG_VOL) Log.d(TAG, "Touch exploration enabled=" + touchExploreEnabled
5275 + " stream override delay is now " + sDelayMs + " ms");
5276 }
5277 }
5278
5279 //==========================================================================================
Eric Laurentdd45d012012-10-08 09:04:34 -07005280 // Camera shutter sound policy.
5281 // config_camera_sound_forced configuration option in config.xml defines if the camera shutter
5282 // sound is forced (sound even if the device is in silent mode) or not. This option is false by
5283 // default and can be overridden by country specific overlay in values-mccXXX/config.xml.
5284 //==========================================================================================
5285
5286 // cached value of com.android.internal.R.bool.config_camera_sound_forced
5287 private Boolean mCameraSoundForced;
5288
5289 // called by android.hardware.Camera to populate CameraInfo.canDisableShutterSound
5290 public boolean isCameraSoundForced() {
5291 synchronized (mCameraSoundForced) {
5292 return mCameraSoundForced;
5293 }
5294 }
5295
5296 private static final String[] RINGER_MODE_NAMES = new String[] {
5297 "SILENT",
5298 "VIBRATE",
5299 "NORMAL"
5300 };
5301
5302 private void dumpRingerMode(PrintWriter pw) {
5303 pw.println("\nRinger mode: ");
John Spurlock661f2cf2014-11-17 10:29:10 -05005304 pw.println("- mode (internal) = " + RINGER_MODE_NAMES[mRingerMode]);
5305 pw.println("- mode (external) = " + RINGER_MODE_NAMES[mRingerModeExternal]);
Eric Laurentdd45d012012-10-08 09:04:34 -07005306 pw.print("- ringer mode affected streams = 0x");
5307 pw.println(Integer.toHexString(mRingerModeAffectedStreams));
5308 pw.print("- ringer mode muted streams = 0x");
5309 pw.println(Integer.toHexString(mRingerModeMutedStreams));
John Spurlock661f2cf2014-11-17 10:29:10 -05005310 pw.print("- delegate = "); pw.println(mRingerModeDelegate);
Eric Laurentdd45d012012-10-08 09:04:34 -07005311 }
5312
Dianne Hackborn632ca412012-06-14 19:34:10 -07005313 @Override
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005314 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5316
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005317 mMediaFocusControl.dump(pw);
Eric Laurentbffc3d12012-05-07 17:43:49 -07005318 dumpStreamStates(pw);
Eric Laurentdd45d012012-10-08 09:04:34 -07005319 dumpRingerMode(pw);
Dianne Hackborn632ca412012-06-14 19:34:10 -07005320 pw.println("\nAudio routes:");
John Spurlock61560172015-02-06 19:46:04 -05005321 pw.print(" mMainType=0x"); pw.println(Integer.toHexString(mCurAudioRoutes.mainType));
5322 pw.print(" mBluetoothName="); pw.println(mCurAudioRoutes.bluetoothName);
John Spurlock35134602014-07-24 18:10:48 -04005323
5324 pw.println("\nOther state:");
John Spurlock3346a802014-05-20 16:25:37 -04005325 pw.print(" mVolumeController="); pw.println(mVolumeController);
John Spurlock35134602014-07-24 18:10:48 -04005326 pw.print(" mSafeMediaVolumeState=");
5327 pw.println(safeMediaVolumeStateToString(mSafeMediaVolumeState));
5328 pw.print(" mSafeMediaVolumeIndex="); pw.println(mSafeMediaVolumeIndex);
5329 pw.print(" mPendingVolumeCommand="); pw.println(mPendingVolumeCommand);
5330 pw.print(" mMusicActiveMs="); pw.println(mMusicActiveMs);
John Spurlockaa5ee4d2014-07-25 13:05:12 -04005331 pw.print(" mMcc="); pw.println(mMcc);
John Spurlock5e783732015-02-19 10:28:59 -05005332 pw.print(" mCameraSoundForced="); pw.println(mCameraSoundForced);
John Spurlock661f2cf2014-11-17 10:29:10 -05005333 pw.print(" mHasVibrator="); pw.println(mHasVibrator);
John Spurlockcdb57ae2015-02-11 19:04:11 -05005334 pw.print(" mControllerService="); pw.println(mControllerService);
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005335
5336 dumpAudioPolicies(pw);
John Spurlock35134602014-07-24 18:10:48 -04005337 }
5338
5339 private static String safeMediaVolumeStateToString(Integer state) {
5340 switch(state) {
5341 case SAFE_MEDIA_VOLUME_NOT_CONFIGURED: return "SAFE_MEDIA_VOLUME_NOT_CONFIGURED";
5342 case SAFE_MEDIA_VOLUME_DISABLED: return "SAFE_MEDIA_VOLUME_DISABLED";
5343 case SAFE_MEDIA_VOLUME_INACTIVE: return "SAFE_MEDIA_VOLUME_INACTIVE";
5344 case SAFE_MEDIA_VOLUME_ACTIVE: return "SAFE_MEDIA_VOLUME_ACTIVE";
5345 }
5346 return null;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005347 }
Glenn Kastenfd116ad2013-07-12 17:10:39 -07005348
5349 // Inform AudioFlinger of our device's low RAM attribute
5350 private static void readAndSetLowRamDevice()
5351 {
5352 int status = AudioSystem.setLowRamDevice(ActivityManager.isLowRamDeviceStatic());
5353 if (status != 0) {
5354 Log.w(TAG, "AudioFlinger informed of device's low RAM attribute; status " + status);
5355 }
5356 }
John Spurlock3346a802014-05-20 16:25:37 -04005357
John Spurlockcdb57ae2015-02-11 19:04:11 -05005358 private void enforceVolumeController(String action) {
5359 if (mControllerService.mUid != 0 && Binder.getCallingUid() == mControllerService.mUid) {
5360 return;
5361 }
John Spurlock3346a802014-05-20 16:25:37 -04005362 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
5363 "Only SystemUI can " + action);
5364 }
5365
5366 @Override
5367 public void setVolumeController(final IVolumeController controller) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005368 enforceVolumeController("set the volume controller");
John Spurlock3346a802014-05-20 16:25:37 -04005369
5370 // return early if things are not actually changing
5371 if (mVolumeController.isSameBinder(controller)) {
5372 return;
5373 }
5374
5375 // dismiss the old volume controller
5376 mVolumeController.postDismiss();
5377 if (controller != null) {
5378 // we are about to register a new controller, listen for its death
5379 try {
5380 controller.asBinder().linkToDeath(new DeathRecipient() {
5381 @Override
5382 public void binderDied() {
5383 if (mVolumeController.isSameBinder(controller)) {
5384 Log.w(TAG, "Current remote volume controller died, unregistering");
5385 setVolumeController(null);
5386 }
5387 }
5388 }, 0);
5389 } catch (RemoteException e) {
5390 // noop
5391 }
5392 }
5393 mVolumeController.setController(controller);
John Spurlock33f4e042014-07-11 13:10:58 -04005394 if (DEBUG_VOL) Log.d(TAG, "Volume controller: " + mVolumeController);
5395 }
5396
5397 @Override
5398 public void notifyVolumeControllerVisible(final IVolumeController controller, boolean visible) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005399 enforceVolumeController("notify about volume controller visibility");
John Spurlock33f4e042014-07-11 13:10:58 -04005400
5401 // return early if the controller is not current
5402 if (!mVolumeController.isSameBinder(controller)) {
5403 return;
5404 }
5405
5406 mVolumeController.setVisible(visible);
5407 if (DEBUG_VOL) Log.d(TAG, "Volume controller visible: " + visible);
John Spurlock3346a802014-05-20 16:25:37 -04005408 }
RoboErikd09bd0c2014-06-24 17:45:19 -07005409
5410 public static class VolumeController {
5411 private static final String TAG = "VolumeController";
5412
5413 private IVolumeController mController;
John Spurlock33f4e042014-07-11 13:10:58 -04005414 private boolean mVisible;
5415 private long mNextLongPress;
5416 private int mLongPressTimeout;
RoboErikd09bd0c2014-06-24 17:45:19 -07005417
5418 public void setController(IVolumeController controller) {
5419 mController = controller;
John Spurlock33f4e042014-07-11 13:10:58 -04005420 mVisible = false;
5421 }
5422
5423 public void loadSettings(ContentResolver cr) {
5424 mLongPressTimeout = Settings.Secure.getIntForUser(cr,
5425 Settings.Secure.LONG_PRESS_TIMEOUT, 500, UserHandle.USER_CURRENT);
5426 }
5427
RoboErik4197cb62015-01-21 15:45:32 -08005428 public boolean suppressAdjustment(int resolvedStream, int flags, boolean isMute) {
5429 if (isMute) {
5430 return false;
5431 }
John Spurlock33f4e042014-07-11 13:10:58 -04005432 boolean suppress = false;
5433 if (resolvedStream == AudioSystem.STREAM_RING && mController != null) {
5434 final long now = SystemClock.uptimeMillis();
5435 if ((flags & AudioManager.FLAG_SHOW_UI) != 0 && !mVisible) {
5436 // ui will become visible
5437 if (mNextLongPress < now) {
5438 mNextLongPress = now + mLongPressTimeout;
5439 }
5440 suppress = true;
5441 } else if (mNextLongPress > 0) { // in a long-press
5442 if (now > mNextLongPress) {
5443 // long press triggered, no more suppression
5444 mNextLongPress = 0;
5445 } else {
5446 // keep suppressing until the long press triggers
5447 suppress = true;
5448 }
5449 }
5450 }
5451 return suppress;
5452 }
5453
5454 public void setVisible(boolean visible) {
5455 mVisible = visible;
RoboErikd09bd0c2014-06-24 17:45:19 -07005456 }
5457
5458 public boolean isSameBinder(IVolumeController controller) {
5459 return Objects.equals(asBinder(), binder(controller));
5460 }
5461
5462 public IBinder asBinder() {
5463 return binder(mController);
5464 }
5465
5466 private static IBinder binder(IVolumeController controller) {
5467 return controller == null ? null : controller.asBinder();
5468 }
5469
5470 @Override
5471 public String toString() {
John Spurlock33f4e042014-07-11 13:10:58 -04005472 return "VolumeController(" + asBinder() + ",mVisible=" + mVisible + ")";
RoboErikd09bd0c2014-06-24 17:45:19 -07005473 }
5474
5475 public void postDisplaySafeVolumeWarning(int flags) {
5476 if (mController == null)
5477 return;
5478 try {
5479 mController.displaySafeVolumeWarning(flags);
5480 } catch (RemoteException e) {
5481 Log.w(TAG, "Error calling displaySafeVolumeWarning", e);
5482 }
5483 }
5484
5485 public void postVolumeChanged(int streamType, int flags) {
5486 if (mController == null)
5487 return;
5488 try {
5489 mController.volumeChanged(streamType, flags);
5490 } catch (RemoteException e) {
5491 Log.w(TAG, "Error calling volumeChanged", e);
5492 }
5493 }
5494
RoboErikd09bd0c2014-06-24 17:45:19 -07005495 public void postMasterMuteChanged(int flags) {
5496 if (mController == null)
5497 return;
5498 try {
5499 mController.masterMuteChanged(flags);
5500 } catch (RemoteException e) {
5501 Log.w(TAG, "Error calling masterMuteChanged", e);
5502 }
5503 }
5504
5505 public void setLayoutDirection(int layoutDirection) {
5506 if (mController == null)
5507 return;
5508 try {
5509 mController.setLayoutDirection(layoutDirection);
5510 } catch (RemoteException e) {
5511 Log.w(TAG, "Error calling setLayoutDirection", e);
5512 }
5513 }
5514
5515 public void postDismiss() {
5516 if (mController == null)
5517 return;
5518 try {
5519 mController.dismiss();
5520 } catch (RemoteException e) {
5521 Log.w(TAG, "Error calling dismiss", e);
5522 }
5523 }
5524 }
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005525
RoboErik0dac35a2014-08-12 15:48:49 -07005526 /**
5527 * Interface for system components to get some extra functionality through
5528 * LocalServices.
5529 */
5530 final class AudioServiceInternal extends AudioManagerInternal {
John Spurlock661f2cf2014-11-17 10:29:10 -05005531 @Override
5532 public void setRingerModeDelegate(RingerModeDelegate delegate) {
5533 mRingerModeDelegate = delegate;
5534 if (mRingerModeDelegate != null) {
5535 setRingerModeInternal(getRingerModeInternal(), TAG + ".setRingerModeDelegate");
5536 }
5537 }
RoboErik272e1612014-09-05 11:39:29 -07005538
5539 @Override
5540 public void adjustSuggestedStreamVolumeForUid(int streamType, int direction, int flags,
5541 String callingPackage, int uid) {
5542 // direction and stream type swap here because the public
5543 // adjustSuggested has a different order than the other methods.
5544 adjustSuggestedStreamVolume(direction, streamType, flags, callingPackage, uid);
5545 }
5546
RoboErik0dac35a2014-08-12 15:48:49 -07005547 @Override
5548 public void adjustStreamVolumeForUid(int streamType, int direction, int flags,
5549 String callingPackage, int uid) {
5550 adjustStreamVolume(streamType, direction, flags, callingPackage, uid);
5551 }
5552
5553 @Override
5554 public void setStreamVolumeForUid(int streamType, int direction, int flags,
5555 String callingPackage, int uid) {
5556 setStreamVolume(streamType, direction, flags, callingPackage, uid);
5557 }
RoboErik519c7742014-11-18 10:59:09 -08005558
5559 @Override
John Spurlock661f2cf2014-11-17 10:29:10 -05005560 public int getRingerModeInternal() {
5561 return AudioService.this.getRingerModeInternal();
5562 }
5563
5564 @Override
5565 public void setRingerModeInternal(int ringerMode, String caller) {
5566 AudioService.this.setRingerModeInternal(ringerMode, caller);
5567 }
John Spurlockcdb57ae2015-02-11 19:04:11 -05005568
5569 @Override
5570 public int getVolumeControllerUid() {
5571 return mControllerService.mUid;
5572 }
RoboErik0dac35a2014-08-12 15:48:49 -07005573 }
5574
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005575 //==========================================================================================
5576 // Audio policy management
5577 //==========================================================================================
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005578 public String registerAudioPolicy(AudioPolicyConfig policyConfig, IAudioPolicyCallback pcb,
5579 boolean hasFocusListener) {
5580 if (DEBUG_AP) Log.d(TAG, "registerAudioPolicy for " + pcb.asBinder()
5581 + " with config:" + policyConfig);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005582 String regId = null;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005583 // error handling
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005584 boolean hasPermissionForPolicy =
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005585 (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission(
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005586 android.Manifest.permission.MODIFY_AUDIO_ROUTING));
5587 if (!hasPermissionForPolicy) {
5588 Slog.w(TAG, "Can't register audio policy for pid " + Binder.getCallingPid() + " / uid "
5589 + Binder.getCallingUid() + ", need MODIFY_AUDIO_ROUTING");
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005590 return null;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005591 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005592
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005593 synchronized (mAudioPolicies) {
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005594 try {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005595 if (mAudioPolicies.containsKey(pcb.asBinder())) {
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005596 Slog.e(TAG, "Cannot re-register policy");
5597 return null;
5598 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005599 AudioPolicyProxy app = new AudioPolicyProxy(policyConfig, pcb, hasFocusListener);
5600 pcb.asBinder().linkToDeath(app, 0/*flags*/);
5601 regId = app.getRegistrationId();
5602 mAudioPolicies.put(pcb.asBinder(), app);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005603 } catch (RemoteException e) {
5604 // audio policy owner has already died!
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005605 Slog.w(TAG, "Audio policy registration failed, could not link to " + pcb +
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005606 " binder death", e);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005607 return null;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005608 }
5609 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005610 return regId;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005611 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005612
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005613 public void unregisterAudioPolicyAsync(IAudioPolicyCallback pcb) {
5614 if (DEBUG_AP) Log.d(TAG, "unregisterAudioPolicyAsync for " + pcb.asBinder());
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005615 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005616 AudioPolicyProxy app = mAudioPolicies.remove(pcb.asBinder());
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005617 if (app == null) {
5618 Slog.w(TAG, "Trying to unregister unknown audio policy for pid "
5619 + Binder.getCallingPid() + " / uid " + Binder.getCallingUid());
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005620 return;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005621 } else {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005622 pcb.asBinder().unlinkToDeath(app, 0/*flags*/);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005623 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005624 app.release();
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005625 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005626 // TODO implement clearing mix attribute matching info in native audio policy
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005627 }
5628
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005629 public int setFocusPropertiesForPolicy(int duckingBehavior, IAudioPolicyCallback pcb) {
5630 if (DEBUG_AP) Log.d(TAG, "setFocusPropertiesForPolicy() duck behavior=" + duckingBehavior
5631 + " policy " + pcb.asBinder());
5632 // error handling
5633 boolean hasPermissionForPolicy =
5634 (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission(
5635 android.Manifest.permission.MODIFY_AUDIO_ROUTING));
5636 if (!hasPermissionForPolicy) {
5637 Slog.w(TAG, "Cannot change audio policy ducking handling for pid " +
5638 + Binder.getCallingPid() + " / uid "
5639 + Binder.getCallingUid() + ", need MODIFY_AUDIO_ROUTING");
5640 return AudioManager.ERROR;
5641 }
5642
5643 synchronized (mAudioPolicies) {
5644 if (!mAudioPolicies.containsKey(pcb.asBinder())) {
5645 Slog.e(TAG, "Cannot change audio policy focus properties, unregistered policy");
5646 return AudioManager.ERROR;
5647 }
5648 final AudioPolicyProxy app = mAudioPolicies.get(pcb.asBinder());
5649 if (duckingBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5650 // is there already one policy managing ducking?
5651 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
5652 if (policy.mFocusDuckBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5653 Slog.e(TAG, "Cannot change audio policy ducking behavior, already handled");
5654 return AudioManager.ERROR;
5655 }
5656 }
5657 }
5658 app.mFocusDuckBehavior = duckingBehavior;
5659 mMediaFocusControl.setDuckingInExtPolicyAvailable(
5660 duckingBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY);
5661 }
5662 return AudioManager.SUCCESS;
5663 }
5664
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005665 private void dumpAudioPolicies(PrintWriter pw) {
5666 pw.println("\nAudio policies:");
5667 synchronized (mAudioPolicies) {
5668 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
5669 pw.println(policy.toLogFriendlyString());
5670 }
5671 }
5672 }
5673
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005674 //======================
5675 // Audio policy proxy
5676 //======================
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005677 /**
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005678 * This internal class inherits from AudioPolicyConfig, each instance contains all the
5679 * mixes of an AudioPolicy and their configurations.
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005680 */
5681 public class AudioPolicyProxy extends AudioPolicyConfig implements IBinder.DeathRecipient {
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005682 private static final String TAG = "AudioPolicyProxy";
5683 AudioPolicyConfig mConfig;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005684 IAudioPolicyCallback mPolicyToken;
5685 boolean mHasFocusListener;
5686 /**
5687 * Audio focus ducking behavior for an audio policy.
5688 * This variable reflects the value that was successfully set in
5689 * {@link AudioService#setFocusPropertiesForPolicy(int, IAudioPolicyCallback)}. This
5690 * implies that a value of FOCUS_POLICY_DUCKING_IN_POLICY means the corresponding policy
5691 * is handling ducking for audio focus.
5692 */
5693 int mFocusDuckBehavior = AudioPolicy.FOCUS_POLICY_DUCKING_DEFAULT;
5694
5695 AudioPolicyProxy(AudioPolicyConfig config, IAudioPolicyCallback token,
5696 boolean hasFocusListener) {
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005697 super(config);
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005698 setRegistration(new String(config.hashCode() + ":ap:" + mAudioPolicyCounter++));
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005699 mPolicyToken = token;
5700 mHasFocusListener = hasFocusListener;
5701 if (mHasFocusListener) {
5702 mMediaFocusControl.addFocusFollower(mPolicyToken);
5703 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005704 connectMixes();
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005705 }
5706
5707 public void binderDied() {
5708 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005709 Log.i(TAG, "audio policy " + mPolicyToken + " died");
5710 release();
5711 mAudioPolicies.remove(mPolicyToken.asBinder());
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005712 }
5713 }
5714
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005715 String getRegistrationId() {
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005716 return getRegistration();
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005717 }
5718
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005719 void release() {
5720 if (mFocusDuckBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5721 mMediaFocusControl.setDuckingInExtPolicyAvailable(false);
5722 }
5723 if (mHasFocusListener) {
5724 mMediaFocusControl.removeFocusFollower(mPolicyToken);
5725 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005726 AudioSystem.registerPolicyMixes(mMixes, false);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005727 }
5728
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005729 void connectMixes() {
5730 AudioSystem.registerPolicyMixes(mMixes, true);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005731 }
5732 };
5733
5734 private HashMap<IBinder, AudioPolicyProxy> mAudioPolicies =
5735 new HashMap<IBinder, AudioPolicyProxy>();
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005736 private int mAudioPolicyCounter = 0; // always accessed synchronized on mAudioPolicies
John Spurlockcdb57ae2015-02-11 19:04:11 -05005737
5738 private class ControllerService extends ContentObserver {
5739 private int mUid;
5740 private ComponentName mComponent;
5741
5742 public ControllerService() {
5743 super(null);
5744 }
5745
5746 @Override
5747 public String toString() {
5748 return String.format("{mUid=%d,mComponent=%s}", mUid, mComponent);
5749 }
5750
5751 public void init() {
5752 onChange(true);
5753 mContentResolver.registerContentObserver(Settings.Secure.getUriFor(
5754 Settings.Secure.VOLUME_CONTROLLER_SERVICE_COMPONENT), false, this);
5755 }
5756
5757 @Override
5758 public void onChange(boolean selfChange) {
5759 mUid = 0;
5760 mComponent = null;
5761 final String setting = Settings.Secure.getString(mContentResolver,
5762 Settings.Secure.VOLUME_CONTROLLER_SERVICE_COMPONENT);
5763 if (setting == null) return;
5764 try {
5765 mComponent = ComponentName.unflattenFromString(setting);
5766 if (mComponent == null) return;
5767 mUid = mContext.getPackageManager()
5768 .getApplicationInfo(mComponent.getPackageName(), 0).uid;
5769 } catch (Exception e) {
5770 Log.w(TAG, "Error loading controller service", e);
5771 }
5772 if (DEBUG_VOL) Log.d(TAG, "Reloaded controller service: " + this);
5773 }
5774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775}