blob: 201b1b705a2d637804e7cb98f74cd5845b15ae3f [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;
57import android.media.AudioSystem;
58import android.media.IAudioFocusDispatcher;
59import android.media.IAudioRoutesObserver;
60import android.media.IAudioService;
61import android.media.IRemoteControlDisplay;
62import android.media.IRingtonePlayer;
63import android.media.IVolumeController;
64import android.media.MediaPlayer;
65import android.media.SoundPool;
66import android.media.AudioAttributes.Builder;
67import android.media.AudioManagerInternal.RingerModeDelegate;
68import android.media.AudioSystem.ErrorCallback;
69import android.media.IAudioService.Stub;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.media.MediaPlayer.OnCompletionListener;
71import android.media.MediaPlayer.OnErrorListener;
John Spurlock61560172015-02-06 19:46:04 -050072import android.media.SoundPool.OnLoadCompleteListener;
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -070073import android.media.audiopolicy.AudioMix;
Jean-Michel Trivi958876f2014-11-16 15:40:22 -080074import android.media.audiopolicy.AudioPolicy;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -070075import android.media.audiopolicy.AudioPolicyConfig;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -080076import android.media.audiopolicy.IAudioPolicyCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Binder;
Eric Laurentc18c9132013-04-12 17:24:56 -070078import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Environment;
80import android.os.Handler;
81import android.os.IBinder;
82import android.os.Looper;
83import android.os.Message;
Jean-Michel Trivic6802222012-04-30 11:15:03 -070084import android.os.PowerManager;
Dianne Hackborn632ca412012-06-14 19:34:10 -070085import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.RemoteException;
John Spurlock33f4e042014-07-11 13:10:58 -040087import android.os.SystemClock;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -070088import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070089import android.os.UserHandle;
Eric Laurentbffc3d12012-05-07 17:43:49 -070090import android.os.Vibrator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.provider.Settings;
92import android.provider.Settings.System;
Tyler Gunnef9f6f92014-09-12 22:16:17 -070093import android.telecom.TelecomManager;
Dianne Hackborn632ca412012-06-14 19:34:10 -070094import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.util.Log;
John Spurlockaa5ee4d2014-07-25 13:05:12 -040096import android.util.MathUtils;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -070097import android.util.Slog;
Jean-Michel Trivid327f212010-03-16 21:44:33 -070098import android.view.KeyEvent;
RoboErik519c7742014-11-18 10:59:09 -080099import android.view.OrientationEventListener;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700100import android.view.Surface;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700101import android.view.WindowManager;
Jean-Michel Trivi873cc452014-09-11 17:25:09 -0700102import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Eric Laurente78fced2013-03-15 16:03:47 -0700104import com.android.internal.util.XmlUtils;
RoboErik0dac35a2014-08-12 15:48:49 -0700105import com.android.server.LocalServices;
Eric Laurente78fced2013-03-15 16:03:47 -0700106
107import org.xmlpull.v1.XmlPullParserException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -0800109import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.io.IOException;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -0800111import java.io.PrintWriter;
Eric Laurente78fced2013-03-15 16:03:47 -0700112import java.lang.reflect.Field;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.ArrayList;
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700114import java.util.HashMap;
115import java.util.Iterator;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700116import java.util.List;
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700117import java.util.Map;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700118import java.util.NoSuchElementException;
RoboErikd09bd0c2014-06-24 17:45:19 -0700119import java.util.Objects;
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700120import java.util.Set;
RoboErik519c7742014-11-18 10:59:09 -0800121import java.util.concurrent.ConcurrentHashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
123/**
124 * The implementation of the volume manager service.
125 * <p>
126 * This implementation focuses on delivering a responsive UI. Most methods are
127 * asynchronous to external calls. For example, the task of setting a volume
128 * will update our internal state, but in a separate thread will set the system
129 * volume and later persist to the database. Similarly, setting the ringer mode
130 * will update the state and broadcast a change and in a separate thread later
131 * persist the ringer mode.
132 *
133 * @hide
134 */
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700135public class AudioService extends IAudioService.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
137 private static final String TAG = "AudioService";
138
Jean-Michel Trivi339567d2014-07-29 09:53:34 -0700139 /** Debug audio mode */
140 protected static final boolean DEBUG_MODE = Log.isLoggable(TAG + ".MOD", Log.DEBUG);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -0700141
142 /** Debug audio policy feature */
143 protected static final boolean DEBUG_AP = Log.isLoggable(TAG + ".AP", Log.DEBUG);
144
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700145 /** Debug volumes */
John Spurlockae641c92014-06-30 18:11:40 -0400146 protected static final boolean DEBUG_VOL = Log.isLoggable(TAG + ".VOL", Log.DEBUG);
Jean-Michel Trivi18e7bce2011-08-26 12:11:36 -0700147
RoboErik430fc482014-06-12 15:49:20 -0700148 /** debug calls to media session apis */
John Spurlockae641c92014-06-30 18:11:40 -0400149 private static final boolean DEBUG_SESSIONS = Log.isLoggable(TAG + ".SESSIONS", Log.DEBUG);
RoboErik8a2cfc32014-05-16 11:19:38 -0700150
John Spurlock86005342014-05-23 11:58:00 -0400151 /** Allow volume changes to set ringer mode to silent? */
152 private static final boolean VOLUME_SETS_RINGER_MODE_SILENT = false;
153
John Spurlocka11b4af2014-06-01 11:52:23 -0400154 /** In silent mode, are volume adjustments (raises) prevented? */
155 private static final boolean PREVENT_VOLUME_ADJUSTMENT_IF_SILENT = true;
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 /** How long to delay before persisting a change in volume/ringer mode. */
RoboErik45edba12012-03-27 17:54:36 -0700158 private static final int PERSIST_DELAY = 500;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
RoboErik5452e252015-02-06 15:33:53 -0800160 /** How long to delay after a volume down event before unmuting a stream */
161 private static final int UNMUTE_STREAM_DELAY = 350;
162
John Spurlock3346a802014-05-20 16:25:37 -0400163 /**
John Spurlocka11b4af2014-06-01 11:52:23 -0400164 * Only used in the result from {@link #checkForRingerModeChange(int, int, int)}
165 */
166 private static final int FLAG_ADJUST_VOLUME = 1;
167
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700168 private final Context mContext;
169 private final ContentResolver mContentResolver;
170 private final AppOpsManager mAppOps;
Eric Laurent212532b2014-07-21 15:43:18 -0700171
Eric Laurent212532b2014-07-21 15:43:18 -0700172 // the platform type affects volume and silent mode behavior
173 private final int mPlatformType;
174
175 private boolean isPlatformVoice() {
John Spurlock61560172015-02-06 19:46:04 -0500176 return mPlatformType == AudioSystem.PLATFORM_VOICE;
Eric Laurent212532b2014-07-21 15:43:18 -0700177 }
178
179 private boolean isPlatformTelevision() {
John Spurlock61560172015-02-06 19:46:04 -0500180 return mPlatformType == AudioSystem.PLATFORM_TELEVISION;
Eric Laurent212532b2014-07-21 15:43:18 -0700181 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -0800182
John Spurlock3346a802014-05-20 16:25:37 -0400183 /** The controller for the volume UI. */
184 private final VolumeController mVolumeController = new VolumeController();
John Spurlockcdb57ae2015-02-11 19:04:11 -0500185 private final ControllerService mControllerService = new ControllerService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
187 // sendMsg() flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 /** If the msg is already queued, replace it with this one. */
189 private static final int SENDMSG_REPLACE = 0;
190 /** If the msg is already queued, ignore this one and leave the old. */
191 private static final int SENDMSG_NOOP = 1;
192 /** If the msg is already queued, queue this one and leave the old. */
193 private static final int SENDMSG_QUEUE = 2;
194
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700195 // AudioHandler messages
Eric Laurent9bc8358d2011-11-18 16:43:31 -0800196 private static final int MSG_SET_DEVICE_VOLUME = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 private static final int MSG_PERSIST_VOLUME = 1;
Mike Lockwood5c55a052011-12-15 17:21:44 -0500198 private static final int MSG_PERSIST_MASTER_VOLUME = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 private static final int MSG_PERSIST_RINGER_MODE = 3;
Eric Laurentbffc3d12012-05-07 17:43:49 -0700200 private static final int MSG_MEDIA_SERVER_DIED = 4;
Eric Laurentdfb881f2013-07-18 14:41:39 -0700201 private static final int MSG_PLAY_SOUND_EFFECT = 5;
202 private static final int MSG_BTA2DP_DOCK_TIMEOUT = 6;
203 private static final int MSG_LOAD_SOUND_EFFECTS = 7;
204 private static final int MSG_SET_FORCE_USE = 8;
205 private static final int MSG_BT_HEADSET_CNCT_FAILED = 9;
206 private static final int MSG_SET_ALL_VOLUMES = 10;
207 private static final int MSG_PERSIST_MASTER_VOLUME_MUTE = 11;
208 private static final int MSG_REPORT_NEW_ROUTES = 12;
209 private static final int MSG_SET_FORCE_BT_A2DP_USE = 13;
210 private static final int MSG_CHECK_MUSIC_ACTIVE = 14;
211 private static final int MSG_BROADCAST_AUDIO_BECOMING_NOISY = 15;
212 private static final int MSG_CONFIGURE_SAFE_MEDIA_VOLUME = 16;
213 private static final int MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED = 17;
214 private static final int MSG_PERSIST_SAFE_VOLUME_STATE = 18;
215 private static final int MSG_BROADCAST_BT_CONNECTION_STATE = 19;
216 private static final int MSG_UNLOAD_SOUND_EFFECTS = 20;
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700217 private static final int MSG_SYSTEM_READY = 21;
John Spurlockaa5ee4d2014-07-25 13:05:12 -0400218 private static final int MSG_PERSIST_MUSIC_ACTIVE_MS = 22;
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400219 private static final int MSG_PERSIST_MICROPHONE_MUTE = 23;
RoboErik5452e252015-02-06 15:33:53 -0800220 private static final int MSG_UNMUTE_STREAM = 24;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700221 // start of messages handled under wakelock
222 // these messages can only be queued, i.e. sent with queueMsgUnderWakeLock(),
Jean-Michel Trivie12c39b2012-06-06 10:51:58 -0700223 // and not with sendMsg(..., ..., SENDMSG_QUEUE, ...)
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700224 private static final int MSG_SET_WIRED_DEVICE_CONNECTION_STATE = 100;
Mike Lockwood0a40ec22014-05-21 10:08:50 -0700225 private static final int MSG_SET_A2DP_SRC_CONNECTION_STATE = 101;
226 private static final int MSG_SET_A2DP_SINK_CONNECTION_STATE = 102;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700227 // end of messages handled under wakelock
Eric Laurentafbb0472011-12-15 09:04:23 -0800228
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -0700229 private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000;
Eric Laurentdc03c612011-04-01 10:59:41 -0700230 // Timeout for connection to bluetooth headset service
231 private static final int BT_HEADSET_CNCT_TIMEOUT_MS = 3000;
232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 /** @see AudioSystemThread */
234 private AudioSystemThread mAudioSystemThread;
235 /** @see AudioHandler */
236 private AudioHandler mAudioHandler;
237 /** @see VolumeStreamState */
238 private VolumeStreamState[] mStreamStates;
Jason Parekhb1096152009-03-24 17:48:25 -0700239 private SettingsObserver mSettingsObserver;
Eric Laurenta553c252009-07-17 12:17:14 -0700240
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700241 private int mMode = AudioSystem.MODE_NORMAL;
Glenn Kastenba195eb2011-12-13 09:30:40 -0800242 // protects mRingerMode
243 private final Object mSettingsLock = new Object();
Eric Laurent45c90ce2012-04-24 18:44:22 -0700244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 private SoundPool mSoundPool;
Glenn Kasten30c918c2011-11-10 17:56:41 -0800246 private final Object mSoundEffectsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 private static final int NUM_SOUNDPOOL_CHANNELS = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
Mike Lockwood47676902011-11-08 10:31:21 -0800249 // Internally master volume is a float in the 0.0 - 1.0 range,
250 // but to support integer based AudioManager API we translate it to 0 - 100
251 private static final int MAX_MASTER_VOLUME = 100;
252
Lei Zhang6c798972012-03-02 11:40:12 -0800253 // Maximum volume adjust steps allowed in a single batch call.
254 private static final int MAX_BATCH_VOLUME_ADJUST_STEPS = 4;
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 /* Sound effect file names */
257 private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
Eric Laurente78fced2013-03-15 16:03:47 -0700258 private static final List<String> SOUND_EFFECT_FILES = new ArrayList<String>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259
260 /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
261 * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
262 * uses soundpool (second column) */
Eric Laurente78fced2013-03-15 16:03:47 -0700263 private final int[][] SOUND_EFFECT_FILES_MAP = new int[AudioManager.NUM_SOUND_EFFECTS][2];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264
Jared Suttles59820132009-08-13 21:50:52 -0500265 /** @hide Maximum volume index values for audio streams */
Eric Laurent91377de2014-10-10 15:24:04 -0700266 private static int[] MAX_STREAM_VOLUME = new int[] {
Eric Laurent6ee99522009-08-25 06:30:59 -0700267 5, // STREAM_VOICE_CALL
268 7, // STREAM_SYSTEM
269 7, // STREAM_RING
270 15, // STREAM_MUSIC
271 7, // STREAM_ALARM
272 7, // STREAM_NOTIFICATION
273 15, // STREAM_BLUETOOTH_SCO
274 7, // STREAM_SYSTEM_ENFORCED
275 15, // STREAM_DTMF
276 15 // STREAM_TTS
Jared Suttles59820132009-08-13 21:50:52 -0500277 };
Eric Laurent91377de2014-10-10 15:24:04 -0700278
Eric Laurent6d517662012-04-23 18:42:39 -0700279 /* mStreamVolumeAlias[] indicates for each stream if it uses the volume settings
Eric Laurenta553c252009-07-17 12:17:14 -0700280 * of another stream: This avoids multiplying the volume settings for hidden
281 * stream types that follow other stream behavior for volume settings
Eric Laurent6d517662012-04-23 18:42:39 -0700282 * NOTE: do not create loops in aliases!
283 * Some streams alias to different streams according to device category (phone or tablet) or
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700284 * use case (in call vs off call...). See updateStreamVolumeAlias() for more details.
Eric Laurent212532b2014-07-21 15:43:18 -0700285 * mStreamVolumeAlias contains STREAM_VOLUME_ALIAS_VOICE aliases for a voice capable device
286 * (phone), STREAM_VOLUME_ALIAS_TELEVISION for a television or set-top box and
287 * STREAM_VOLUME_ALIAS_DEFAULT for other devices (e.g. tablets).*/
288 private final int[] STREAM_VOLUME_ALIAS_VOICE = new int[] {
Eric Laurent6d517662012-04-23 18:42:39 -0700289 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL
290 AudioSystem.STREAM_RING, // STREAM_SYSTEM
291 AudioSystem.STREAM_RING, // STREAM_RING
292 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
293 AudioSystem.STREAM_ALARM, // STREAM_ALARM
294 AudioSystem.STREAM_RING, // STREAM_NOTIFICATION
295 AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
296 AudioSystem.STREAM_RING, // STREAM_SYSTEM_ENFORCED
297 AudioSystem.STREAM_RING, // STREAM_DTMF
298 AudioSystem.STREAM_MUSIC // STREAM_TTS
Eric Laurenta553c252009-07-17 12:17:14 -0700299 };
Eric Laurent212532b2014-07-21 15:43:18 -0700300 private final int[] STREAM_VOLUME_ALIAS_TELEVISION = new int[] {
301 AudioSystem.STREAM_MUSIC, // STREAM_VOICE_CALL
302 AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM
303 AudioSystem.STREAM_MUSIC, // STREAM_RING
304 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
305 AudioSystem.STREAM_MUSIC, // STREAM_ALARM
306 AudioSystem.STREAM_MUSIC, // STREAM_NOTIFICATION
307 AudioSystem.STREAM_MUSIC, // STREAM_BLUETOOTH_SCO
308 AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM_ENFORCED
309 AudioSystem.STREAM_MUSIC, // STREAM_DTMF
310 AudioSystem.STREAM_MUSIC // STREAM_TTS
311 };
312 private final int[] STREAM_VOLUME_ALIAS_DEFAULT = new int[] {
Eric Laurent6d517662012-04-23 18:42:39 -0700313 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL
John Spurlock4f0f1202014-08-05 13:28:33 -0400314 AudioSystem.STREAM_RING, // STREAM_SYSTEM
Eric Laurent6d517662012-04-23 18:42:39 -0700315 AudioSystem.STREAM_RING, // STREAM_RING
316 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
317 AudioSystem.STREAM_ALARM, // STREAM_ALARM
318 AudioSystem.STREAM_RING, // STREAM_NOTIFICATION
319 AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
John Spurlock4f0f1202014-08-05 13:28:33 -0400320 AudioSystem.STREAM_RING, // STREAM_SYSTEM_ENFORCED
321 AudioSystem.STREAM_RING, // STREAM_DTMF
Eric Laurent6d517662012-04-23 18:42:39 -0700322 AudioSystem.STREAM_MUSIC // STREAM_TTS
323 };
324 private int[] mStreamVolumeAlias;
Eric Laurenta553c252009-07-17 12:17:14 -0700325
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700326 /**
327 * Map AudioSystem.STREAM_* constants to app ops. This should be used
328 * after mapping through mStreamVolumeAlias.
329 */
330 private static final int[] STEAM_VOLUME_OPS = new int[] {
331 AppOpsManager.OP_AUDIO_VOICE_VOLUME, // STREAM_VOICE_CALL
332 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_SYSTEM
333 AppOpsManager.OP_AUDIO_RING_VOLUME, // STREAM_RING
334 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_MUSIC
335 AppOpsManager.OP_AUDIO_ALARM_VOLUME, // STREAM_ALARM
336 AppOpsManager.OP_AUDIO_NOTIFICATION_VOLUME, // STREAM_NOTIFICATION
337 AppOpsManager.OP_AUDIO_BLUETOOTH_VOLUME, // STREAM_BLUETOOTH_SCO
338 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_SYSTEM_ENFORCED
339 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_DTMF
340 AppOpsManager.OP_AUDIO_MEDIA_VOLUME, // STREAM_TTS
341 };
342
Eric Laurent83a017b2013-03-19 18:15:31 -0700343 private final boolean mUseFixedVolume;
344
Glenn Kasten30c918c2011-11-10 17:56:41 -0800345 private final AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 public void onError(int error) {
347 switch (error) {
348 case AudioSystem.AUDIO_STATUS_SERVER_DIED:
Eric Laurentdfb881f2013-07-18 14:41:39 -0700349 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED,
350 SENDMSG_NOOP, 0, 0, null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 break;
352 default:
353 break;
354 }
Eric Laurentdfb881f2013-07-18 14:41:39 -0700355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 };
357
358 /**
359 * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
360 * {@link AudioManager#RINGER_MODE_SILENT}, or
361 * {@link AudioManager#RINGER_MODE_VIBRATE}.
362 */
Glenn Kastenba195eb2011-12-13 09:30:40 -0800363 // protected by mSettingsLock
John Spurlock661f2cf2014-11-17 10:29:10 -0500364 private int mRingerMode; // internal ringer mode, affects muting of underlying streams
365 private int mRingerModeExternal = -1; // reported ringer mode to outside clients (AudioManager)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366
Eric Laurent9bcf4012009-06-12 06:09:28 -0700367 /** @see System#MODE_RINGER_STREAMS_AFFECTED */
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700368 private int mRingerModeAffectedStreams = 0;
Eric Laurent9bcf4012009-06-12 06:09:28 -0700369
Eric Laurent5b4e6542010-03-19 20:02:21 -0700370 // Streams currently muted by ringer mode
371 private int mRingerModeMutedStreams;
372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 /** @see System#MUTE_STREAMS_AFFECTED */
374 private int mMuteAffectedStreams;
375
376 /**
Eric Laurentbffc3d12012-05-07 17:43:49 -0700377 * NOTE: setVibrateSetting(), getVibrateSetting(), shouldVibrate() are deprecated.
378 * mVibrateSetting is just maintained during deprecation period but vibration policy is
379 * now only controlled by mHasVibrator and mRingerMode
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 */
381 private int mVibrateSetting;
382
Eric Laurentbffc3d12012-05-07 17:43:49 -0700383 // Is there a vibrator
384 private final boolean mHasVibrator;
385
Eric Laurenta553c252009-07-17 12:17:14 -0700386 // Broadcast receiver for device connections intent broadcasts
387 private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
388
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700389 // Devices currently connected
Glenn Kasten30c918c2011-11-10 17:56:41 -0800390 private final HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700391
392 // Forced device usage for communications
393 private int mForcedUseForComm;
394
Mike Lockwood0dc37cc2011-12-01 16:14:19 -0500395 // True if we have master volume support
396 private final boolean mUseMasterVolume;
397
Mike Lockwood97606472012-02-09 11:24:10 -0800398 private final int[] mMasterVolumeRamp;
399
Eric Laurent9272b4b2010-01-23 17:12:59 -0800400 // List of binder death handlers for setMode() client processes.
401 // The last process to have called setMode() is at the top of the list.
Glenn Kasten30c918c2011-11-10 17:56:41 -0800402 private final ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
Eric Laurenteb14a782009-12-17 03:12:59 -0800403
Eric Laurent3def1ee2010-03-17 23:26:26 -0700404 // List of clients having issued a SCO start request
Glenn Kasten30c918c2011-11-10 17:56:41 -0800405 private final ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
Eric Laurent3def1ee2010-03-17 23:26:26 -0700406
407 // BluetoothHeadset API to control SCO connection
408 private BluetoothHeadset mBluetoothHeadset;
409
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700410 // Bluetooth headset device
411 private BluetoothDevice mBluetoothHeadsetDevice;
Eric Laurent3def1ee2010-03-17 23:26:26 -0700412
Eric Laurent62ef7672010-11-24 10:58:32 -0800413 // Indicate if SCO audio connection is currently active and if the initiator is
414 // audio service (internal) or bluetooth headset (external)
415 private int mScoAudioState;
416 // SCO audio state is not active
417 private static final int SCO_STATE_INACTIVE = 0;
Eric Laurentdc03c612011-04-01 10:59:41 -0700418 // SCO audio activation request waiting for headset service to connect
419 private static final int SCO_STATE_ACTIVATE_REQ = 1;
Eric Laurent25fc29b2013-04-05 12:13:54 -0700420 // SCO audio state is active or starting due to a request from AudioManager API
Eric Laurentdc03c612011-04-01 10:59:41 -0700421 private static final int SCO_STATE_ACTIVE_INTERNAL = 3;
422 // SCO audio deactivation request waiting for headset service to connect
423 private static final int SCO_STATE_DEACTIVATE_REQ = 5;
424
Eric Laurent62ef7672010-11-24 10:58:32 -0800425 // SCO audio state is active due to an action in BT handsfree (either voice recognition or
426 // in call audio)
427 private static final int SCO_STATE_ACTIVE_EXTERNAL = 2;
Eric Laurentdc03c612011-04-01 10:59:41 -0700428 // Deactivation request for all SCO connections (initiated by audio mode change)
429 // waiting for headset service to connect
430 private static final int SCO_STATE_DEACTIVATE_EXT_REQ = 4;
431
Eric Laurentc18c9132013-04-12 17:24:56 -0700432 // Indicates the mode used for SCO audio connection. The mode is virtual call if the request
433 // originated from an app targeting an API version before JB MR2 and raw audio after that.
434 private int mScoAudioMode;
Liejun Taof4e51d82014-07-16 11:18:29 -0700435 // SCO audio mode is undefined
436 private static final int SCO_MODE_UNDEFINED = -1;
Eric Laurentc18c9132013-04-12 17:24:56 -0700437 // SCO audio mode is virtual voice call (BluetoothHeadset.startScoUsingVirtualVoiceCall())
438 private static final int SCO_MODE_VIRTUAL_CALL = 0;
439 // SCO audio mode is raw audio (BluetoothHeadset.connectAudio())
440 private static final int SCO_MODE_RAW = 1;
Liejun Taof4e51d82014-07-16 11:18:29 -0700441 // SCO audio mode is Voice Recognition (BluetoothHeadset.startVoiceRecognition())
442 private static final int SCO_MODE_VR = 2;
443
444 private static final int SCO_MODE_MAX = 2;
Eric Laurentc18c9132013-04-12 17:24:56 -0700445
Eric Laurentdc03c612011-04-01 10:59:41 -0700446 // Current connection state indicated by bluetooth headset
447 private int mScoConnectionState;
Eric Laurent62ef7672010-11-24 10:58:32 -0800448
Eric Laurenta60e2122010-12-28 16:49:07 -0800449 // true if boot sequence has been completed
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700450 private boolean mSystemReady;
Eric Laurenta60e2122010-12-28 16:49:07 -0800451 // listener for SoundPool sample load completion indication
452 private SoundPoolCallback mSoundPoolCallBack;
453 // thread for SoundPool listener
454 private SoundPoolListenerThread mSoundPoolListenerThread;
455 // message looper for SoundPool listener
456 private Looper mSoundPoolLooper = null;
Jean-Michel Trivic55b3932012-06-05 11:57:59 -0700457 // volume applied to sound played with playSoundEffect()
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -0700458 private static int sSoundEffectVolumeDb;
Eric Laurent25101b02011-02-02 09:33:30 -0800459 // previous volume adjustment direction received by checkForRingerModeChange()
460 private int mPrevVolDirection = AudioManager.ADJUST_SAME;
Amith Yamasani6243edd2011-12-05 19:58:48 -0800461 // Keyguard manager proxy
462 private KeyguardManager mKeyguardManager;
Eric Laurent45c90ce2012-04-24 18:44:22 -0700463 // mVolumeControlStream is set by VolumePanel to temporarily force the stream type which volume
464 // is controlled by Vol keys.
465 private int mVolumeControlStream = -1;
466 private final Object mForceControlStreamLock = new Object();
467 // VolumePanel is currently the only client of forceVolumeControlStream() and runs in system
468 // server process so in theory it is not necessary to monitor the client death.
469 // However it is good to be ready for future evolutions.
470 private ForceControlStreamClient mForceControlStreamClient = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700471 // Used to play ringtones outside system_server
472 private volatile IRingtonePlayer mRingtonePlayer;
Eric Laurent9bc8358d2011-11-18 16:43:31 -0800473
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700474 private int mDeviceOrientation = Configuration.ORIENTATION_UNDEFINED;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700475 private int mDeviceRotation = Surface.ROTATION_0;
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700476
Eric Laurent78472112012-05-21 08:57:21 -0700477 // Request to override default use of A2DP for media.
478 private boolean mBluetoothA2dpEnabled;
479 private final Object mBluetoothA2dpEnabledLock = new Object();
480
Dianne Hackborn632ca412012-06-14 19:34:10 -0700481 // Monitoring of audio routes. Protected by mCurAudioRoutes.
482 final AudioRoutesInfo mCurAudioRoutes = new AudioRoutesInfo();
483 final RemoteCallbackList<IAudioRoutesObserver> mRoutesObservers
484 = new RemoteCallbackList<IAudioRoutesObserver>();
485
Eric Laurent4bbcc652012-09-24 14:26:30 -0700486 // Devices for which the volume is fixed and VolumePanel slider should be disabled
Eric Laurent212532b2014-07-21 15:43:18 -0700487 int mFixedVolumeDevices = AudioSystem.DEVICE_OUT_HDMI |
Eric Laurent4bbcc652012-09-24 14:26:30 -0700488 AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET |
Eric Laurent212532b2014-07-21 15:43:18 -0700489 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET |
490 AudioSystem.DEVICE_OUT_HDMI_ARC |
491 AudioSystem.DEVICE_OUT_SPDIF |
492 AudioSystem.DEVICE_OUT_AUX_LINE;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -0700493 int mFullVolumeDevices = 0;
Eric Laurent4bbcc652012-09-24 14:26:30 -0700494
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700495 // TODO merge orientation and rotation
Eric Laurentd640bd32012-09-28 18:01:48 -0700496 private final boolean mMonitorOrientation;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700497 private final boolean mMonitorRotation;
Eric Laurentd640bd32012-09-28 18:01:48 -0700498
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700499 private boolean mDockAudioMediaEnabled = true;
500
Eric Laurent08ed1b92012-11-05 14:54:12 -0800501 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
502
Eric Laurentfde16d52012-12-03 14:42:39 -0800503 // Used when safe volume warning message display is requested by setStreamVolume(). In this
504 // case, the new requested volume, stream type and device are stored in mPendingVolumeCommand
505 // and used later when/if disableSafeMediaVolume() is called.
506 private StreamVolumeCommand mPendingVolumeCommand;
507
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700508 private PowerManager.WakeLock mAudioEventWakeLock;
509
510 private final MediaFocusControl mMediaFocusControl;
511
John Du5a0cf7a2013-07-19 11:30:34 -0700512 // Reference to BluetoothA2dp to query for AbsoluteVolume.
513 private BluetoothA2dp mA2dp;
seunghwan.hong4fe77952014-10-29 17:43:20 +0900514 // lock always taken synchronized on mConnectedDevices
John Du5a0cf7a2013-07-19 11:30:34 -0700515 private final Object mA2dpAvrcpLock = new Object();
516 // If absolute volume is supported in AVRCP device
517 private boolean mAvrcpAbsVolSupported = false;
518
Jon Eklund318f0fe2014-01-23 17:53:48 -0600519 private AudioOrientationEventListener mOrientationListener;
520
Eric Laurentadbe8bf2014-11-03 18:26:32 -0800521 private static Long mLastDeviceConnectMsgTime = new Long(0);
522
John Spurlock661f2cf2014-11-17 10:29:10 -0500523 private AudioManagerInternal.RingerModeDelegate mRingerModeDelegate;
524
Paul McLean10804eb2015-01-28 11:16:35 -0800525 // Intent "extra" data keys.
526 public static final String CONNECT_INTENT_KEY_PORT_NAME = "portName";
527 public static final String CONNECT_INTENT_KEY_STATE = "state";
528 public static final String CONNECT_INTENT_KEY_ADDRESS = "address";
529 public static final String CONNECT_INTENT_KEY_HAS_PLAYBACK = "hasPlayback";
530 public static final String CONNECT_INTENT_KEY_HAS_CAPTURE = "hasCapture";
531 public static final String CONNECT_INTENT_KEY_HAS_MIDI = "hasMIDI";
532 public static final String CONNECT_INTENT_KEY_DEVICE_CLASS = "class";
533
534 // Defines the format for the connection "address" for ALSA devices
535 public static String makeAlsaAddressString(int card, int device) {
536 return "card=" + card + ";device=" + device + ";";
537 }
538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 ///////////////////////////////////////////////////////////////////////////
540 // Construction
541 ///////////////////////////////////////////////////////////////////////////
542
543 /** @hide */
544 public AudioService(Context context) {
545 mContext = context;
546 mContentResolver = context.getContentResolver();
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700547 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
Eric Laurent212532b2014-07-21 15:43:18 -0700548
John Spurlock61560172015-02-06 19:46:04 -0500549 mPlatformType = AudioSystem.getPlatformType(context);
Jared Suttles59820132009-08-13 21:50:52 -0500550
Jean-Michel Trivic6802222012-04-30 11:15:03 -0700551 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700552 mAudioEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleAudioEvent");
Jean-Michel Trivic6802222012-04-30 11:15:03 -0700553
Eric Laurentbffc3d12012-05-07 17:43:49 -0700554 Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
555 mHasVibrator = vibrator == null ? false : vibrator.hasVibrator();
556
Jared Suttles59820132009-08-13 21:50:52 -0500557 // Intialized volume
Eric Laurent91377de2014-10-10 15:24:04 -0700558 int maxVolume = SystemProperties.getInt("ro.config.vc_call_vol_steps",
559 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
560 if (maxVolume != MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]) {
561 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = maxVolume;
John Spurlock61560172015-02-06 19:46:04 -0500562 AudioSystem.DEFAULT_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = (maxVolume * 3) / 4;
Eric Laurent91377de2014-10-10 15:24:04 -0700563 }
564 maxVolume = SystemProperties.getInt("ro.config.media_vol_steps",
565 MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
566 if (maxVolume != MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]) {
567 MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC] = maxVolume;
John Spurlock61560172015-02-06 19:46:04 -0500568 AudioSystem.DEFAULT_STREAM_VOLUME[AudioSystem.STREAM_MUSIC] = (maxVolume * 3) / 4;
Eric Laurent91377de2014-10-10 15:24:04 -0700569 }
Jared Suttles59820132009-08-13 21:50:52 -0500570
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -0700571 sSoundEffectVolumeDb = context.getResources().getInteger(
Jean-Michel Trivic55b3932012-06-05 11:57:59 -0700572 com.android.internal.R.integer.config_soundEffectVolumeDb);
Eric Laurent25101b02011-02-02 09:33:30 -0800573
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700574 mForcedUseForComm = AudioSystem.FORCE_NONE;
Eric Laurentdd45d012012-10-08 09:04:34 -0700575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 createAudioSystemThread();
Eric Laurentdd45d012012-10-08 09:04:34 -0700577
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700578 mMediaFocusControl = new MediaFocusControl(mAudioHandler.getLooper(),
John Spurlock3346a802014-05-20 16:25:37 -0400579 mContext, mVolumeController, this);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700580
Eric Laurentdfb881f2013-07-18 14:41:39 -0700581 AudioSystem.setErrorCallback(mAudioSystemCallback);
582
Eric Laurentdd45d012012-10-08 09:04:34 -0700583 boolean cameraSoundForced = mContext.getResources().getBoolean(
584 com.android.internal.R.bool.config_camera_sound_forced);
585 mCameraSoundForced = new Boolean(cameraSoundForced);
586 sendMsg(mAudioHandler,
587 MSG_SET_FORCE_USE,
588 SENDMSG_QUEUE,
589 AudioSystem.FOR_SYSTEM,
590 cameraSoundForced ?
591 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE,
592 null,
593 0);
594
Eric Laurent05274f32012-11-29 12:48:18 -0800595 mSafeMediaVolumeState = new Integer(Settings.Global.getInt(mContentResolver,
596 Settings.Global.AUDIO_SAFE_VOLUME_STATE,
597 SAFE_MEDIA_VOLUME_NOT_CONFIGURED));
598 // The default safe volume index read here will be replaced by the actual value when
599 // the mcc is read by onConfigureSafeVolume()
600 mSafeMediaVolumeIndex = mContext.getResources().getInteger(
601 com.android.internal.R.integer.config_safe_media_volume_index) * 10;
602
Eric Laurent83a017b2013-03-19 18:15:31 -0700603 mUseFixedVolume = mContext.getResources().getBoolean(
604 com.android.internal.R.bool.config_useFixedVolume);
Wally Yauda392902014-11-28 12:40:30 -0800605 mUseMasterVolume = context.getResources().getBoolean(
606 com.android.internal.R.bool.config_useMasterVolume);
607 mMasterVolumeRamp = context.getResources().getIntArray(
608 com.android.internal.R.array.config_masterVolumeRamp);
Eric Laurent83a017b2013-03-19 18:15:31 -0700609
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700610 // must be called before readPersistedSettings() which needs a valid mStreamVolumeAlias[]
611 // array initialized by updateStreamVolumeAlias()
612 updateStreamVolumeAlias(false /*updateVolumes*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 readPersistedSettings();
Eric Laurentc1d41662011-07-19 11:21:13 -0700614 mSettingsObserver = new SettingsObserver();
Eric Laurenta553c252009-07-17 12:17:14 -0700615 createStreamStates();
Eric Laurent9f103de2011-09-08 15:04:23 -0700616
Glenn Kastenfd116ad2013-07-12 17:10:39 -0700617 readAndSetLowRamDevice();
Eric Laurent3891c4c2010-04-20 09:40:57 -0700618
619 // Call setRingerModeInt() to apply correct mute
620 // state on streams affected by ringer mode.
621 mRingerModeMutedStreams = 0;
John Spurlock661f2cf2014-11-17 10:29:10 -0500622 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent3891c4c2010-04-20 09:40:57 -0700623
Eric Laurenta553c252009-07-17 12:17:14 -0700624 // Register for device connection intent broadcasts.
625 IntentFilter intentFilter =
Eric Laurentb1fbaac2012-05-29 09:24:28 -0700626 new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700627 intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
628 intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
Eric Laurent950e8cb2011-10-13 08:57:54 -0700629 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
630 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
Eric Laurentbc0fab1f2012-09-19 11:24:41 -0700631 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Paul McLeanc837a452014-04-09 09:04:43 -0700632 intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700633
Eric Laurentd640bd32012-09-28 18:01:48 -0700634 intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700635 // TODO merge orientation and rotation
Eric Laurentd640bd32012-09-28 18:01:48 -0700636 mMonitorOrientation = SystemProperties.getBoolean("ro.audio.monitorOrientation", false);
637 if (mMonitorOrientation) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700638 Log.v(TAG, "monitoring device orientation");
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700639 // initialize orientation in AudioSystem
640 setOrientationForAudioSystem();
641 }
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700642 mMonitorRotation = SystemProperties.getBoolean("ro.audio.monitorRotation", false);
643 if (mMonitorRotation) {
644 mDeviceRotation = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE))
645 .getDefaultDisplay().getRotation();
646 Log.v(TAG, "monitoring device rotation, initial=" + mDeviceRotation);
Jon Eklund318f0fe2014-01-23 17:53:48 -0600647
648 mOrientationListener = new AudioOrientationEventListener(mContext);
649 mOrientationListener.enable();
650
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700651 // initialize rotation in AudioSystem
652 setRotationForAudioSystem();
653 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700654
Eric Laurenta553c252009-07-17 12:17:14 -0700655 context.registerReceiver(mReceiver, intentFilter);
Jared Suttles59820132009-08-13 21:50:52 -0500656
Mike Lockwood90631542012-01-06 11:20:37 -0500657 restoreMasterVolume();
Mike Lockwood97606472012-02-09 11:24:10 -0800658
RoboErik0dac35a2014-08-12 15:48:49 -0700659 LocalServices.addService(AudioManagerInternal.class, new AudioServiceInternal());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 }
661
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700662 public void systemReady() {
663 sendMsg(mAudioHandler, MSG_SYSTEM_READY, SENDMSG_QUEUE,
664 0, 0, null, 0);
665 }
666
667 public void onSystemReady() {
668 mSystemReady = true;
669 sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_QUEUE,
670 0, 0, null, 0);
671
672 mKeyguardManager =
673 (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
674 mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR;
675 resetBluetoothSco();
676 getBluetoothHeadset();
677 //FIXME: this is to maintain compatibility with deprecated intent
678 // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
679 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
680 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
681 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
682 sendStickyBroadcastToAll(newIntent);
683
684 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
685 if (adapter != null) {
686 adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
687 BluetoothProfile.A2DP);
688 }
689
Eric Laurent212532b2014-07-21 15:43:18 -0700690 mHdmiManager =
Wonsik Kim7f4342e2014-07-20 23:04:59 +0900691 (HdmiControlManager) mContext.getSystemService(Context.HDMI_CONTROL_SERVICE);
Eric Laurent212532b2014-07-21 15:43:18 -0700692 if (mHdmiManager != null) {
693 synchronized (mHdmiManager) {
694 mHdmiTvClient = mHdmiManager.getTvClient();
Jungshik Jangc9ff9682014-09-15 17:41:06 +0900695 if (mHdmiTvClient != null) {
696 mFixedVolumeDevices &= ~AudioSystem.DEVICE_ALL_HDMI_SYSTEM_AUDIO_AND_SPEAKER;
697 }
Eric Laurent212532b2014-07-21 15:43:18 -0700698 mHdmiPlaybackClient = mHdmiManager.getPlaybackClient();
699 mHdmiCecSink = false;
700 }
701 }
Wonsik Kim7f4342e2014-07-20 23:04:59 +0900702
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700703 sendMsg(mAudioHandler,
704 MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED,
705 SENDMSG_REPLACE,
706 0,
707 0,
708 null,
709 SAFE_VOLUME_CONFIGURE_TIMEOUT_MS);
Jean-Michel Trivi873cc452014-09-11 17:25:09 -0700710
711 StreamOverride.init(mContext);
John Spurlockcdb57ae2015-02-11 19:04:11 -0500712 mControllerService.init();
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700713 }
714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 private void createAudioSystemThread() {
716 mAudioSystemThread = new AudioSystemThread();
717 mAudioSystemThread.start();
718 waitForAudioHandlerCreation();
719 }
720
721 /** Waits for the volume handler to be created by the other thread. */
722 private void waitForAudioHandlerCreation() {
723 synchronized(this) {
724 while (mAudioHandler == null) {
725 try {
726 // Wait for mAudioHandler to be set by the other thread
727 wait();
728 } catch (InterruptedException e) {
729 Log.e(TAG, "Interrupted while waiting on volume handler.");
730 }
731 }
732 }
733 }
734
Eric Laurent24482012012-05-10 09:41:17 -0700735 private void checkAllAliasStreamVolumes() {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -0700736 synchronized (VolumeStreamState.class) {
737 int numStreamTypes = AudioSystem.getNumStreamTypes();
738 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
739 if (streamType != mStreamVolumeAlias[streamType]) {
740 mStreamStates[streamType].
Eric Laurent42b041e2013-03-29 11:36:03 -0700741 setAllIndexes(mStreamStates[mStreamVolumeAlias[streamType]]);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -0700742 }
743 // apply stream volume
RoboErik4197cb62015-01-21 15:45:32 -0800744 if (!mStreamStates[streamType].mIsMuted) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -0700745 mStreamStates[streamType].applyAllVolumes();
746 }
Eric Laurent24482012012-05-10 09:41:17 -0700747 }
748 }
749 }
750
Eric Laurent212532b2014-07-21 15:43:18 -0700751 private void checkAllFixedVolumeDevices()
752 {
753 int numStreamTypes = AudioSystem.getNumStreamTypes();
754 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
755 mStreamStates[streamType].checkFixedVolumeDevices();
756 }
757 }
758
Jean-Michel Triviba5270b2014-10-01 17:49:29 -0700759 private void checkAllFixedVolumeDevices(int streamType) {
760 mStreamStates[streamType].checkFixedVolumeDevices();
761 }
762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 private void createStreamStates() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 int numStreamTypes = AudioSystem.getNumStreamTypes();
765 VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
766
767 for (int i = 0; i < numStreamTypes; i++) {
Eric Laurent6d517662012-04-23 18:42:39 -0700768 streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[mStreamVolumeAlias[i]], i);
Eric Laurenta553c252009-07-17 12:17:14 -0700769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770
Eric Laurent212532b2014-07-21 15:43:18 -0700771 checkAllFixedVolumeDevices();
Eric Laurent24482012012-05-10 09:41:17 -0700772 checkAllAliasStreamVolumes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
774
Eric Laurentbffc3d12012-05-07 17:43:49 -0700775 private void dumpStreamStates(PrintWriter pw) {
776 pw.println("\nStream volumes (device: index)");
777 int numStreamTypes = AudioSystem.getNumStreamTypes();
778 for (int i = 0; i < numStreamTypes; i++) {
John Spurlock61560172015-02-06 19:46:04 -0500779 pw.println("- " + AudioSystem.STREAM_NAMES[i] + ":");
Eric Laurentbffc3d12012-05-07 17:43:49 -0700780 mStreamStates[i].dump(pw);
781 pw.println("");
782 }
Eric Laurentdd45d012012-10-08 09:04:34 -0700783 pw.print("\n- mute affected streams = 0x");
784 pw.println(Integer.toHexString(mMuteAffectedStreams));
Eric Laurentbffc3d12012-05-07 17:43:49 -0700785 }
786
Eric Laurent6d517662012-04-23 18:42:39 -0700787 private void updateStreamVolumeAlias(boolean updateVolumes) {
788 int dtmfStreamAlias;
Eric Laurent212532b2014-07-21 15:43:18 -0700789
790 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -0500791 case AudioSystem.PLATFORM_VOICE:
Eric Laurent212532b2014-07-21 15:43:18 -0700792 mStreamVolumeAlias = STREAM_VOLUME_ALIAS_VOICE;
Eric Laurent6d517662012-04-23 18:42:39 -0700793 dtmfStreamAlias = AudioSystem.STREAM_RING;
Eric Laurent212532b2014-07-21 15:43:18 -0700794 break;
John Spurlock61560172015-02-06 19:46:04 -0500795 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -0700796 mStreamVolumeAlias = STREAM_VOLUME_ALIAS_TELEVISION;
797 dtmfStreamAlias = AudioSystem.STREAM_MUSIC;
798 break;
799 default:
800 mStreamVolumeAlias = STREAM_VOLUME_ALIAS_DEFAULT;
Eric Laurent6d517662012-04-23 18:42:39 -0700801 dtmfStreamAlias = AudioSystem.STREAM_MUSIC;
802 }
Eric Laurent212532b2014-07-21 15:43:18 -0700803
804 if (isPlatformTelevision()) {
805 mRingerModeAffectedStreams = 0;
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700806 } else {
Eric Laurent212532b2014-07-21 15:43:18 -0700807 if (isInCommunication()) {
808 dtmfStreamAlias = AudioSystem.STREAM_VOICE_CALL;
809 mRingerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_DTMF);
810 } else {
811 mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_DTMF);
812 }
Eric Laurent6d517662012-04-23 18:42:39 -0700813 }
Eric Laurent212532b2014-07-21 15:43:18 -0700814
Eric Laurent6d517662012-04-23 18:42:39 -0700815 mStreamVolumeAlias[AudioSystem.STREAM_DTMF] = dtmfStreamAlias;
816 if (updateVolumes) {
Eric Laurent42b041e2013-03-29 11:36:03 -0700817 mStreamStates[AudioSystem.STREAM_DTMF].setAllIndexes(mStreamStates[dtmfStreamAlias]);
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700818 // apply stream mute states according to new value of mRingerModeAffectedStreams
John Spurlock661f2cf2014-11-17 10:29:10 -0500819 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent6d517662012-04-23 18:42:39 -0700820 sendMsg(mAudioHandler,
821 MSG_SET_ALL_VOLUMES,
822 SENDMSG_QUEUE,
823 0,
824 0,
825 mStreamStates[AudioSystem.STREAM_DTMF], 0);
826 }
827 }
828
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700829 private void readDockAudioSettings(ContentResolver cr)
830 {
831 mDockAudioMediaEnabled = Settings.Global.getInt(
Eric Laurent5ba0ffa02012-10-29 12:31:09 -0700832 cr, Settings.Global.DOCK_AUDIO_MEDIA_ENABLED, 0) == 1;
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700833
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700834 sendMsg(mAudioHandler,
835 MSG_SET_FORCE_USE,
836 SENDMSG_QUEUE,
837 AudioSystem.FOR_DOCK,
838 mDockAudioMediaEnabled ?
839 AudioSystem.FORCE_ANALOG_DOCK : AudioSystem.FORCE_NONE,
840 null,
841 0);
842 }
843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 private void readPersistedSettings() {
845 final ContentResolver cr = mContentResolver;
846
Eric Laurentbffc3d12012-05-07 17:43:49 -0700847 int ringerModeFromSettings =
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -0700848 Settings.Global.getInt(
849 cr, Settings.Global.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
Eric Laurentbffc3d12012-05-07 17:43:49 -0700850 int ringerMode = ringerModeFromSettings;
Eric Laurent72668b22011-07-19 16:04:27 -0700851 // sanity check in case the settings are restored from a device with incompatible
852 // ringer modes
John Spurlock97559372014-10-24 16:27:36 -0400853 if (!isValidRingerMode(ringerMode)) {
Glenn Kastenba195eb2011-12-13 09:30:40 -0800854 ringerMode = AudioManager.RINGER_MODE_NORMAL;
Eric Laurentbffc3d12012-05-07 17:43:49 -0700855 }
856 if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) {
857 ringerMode = AudioManager.RINGER_MODE_SILENT;
858 }
859 if (ringerMode != ringerModeFromSettings) {
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -0700860 Settings.Global.putInt(cr, Settings.Global.MODE_RINGER, ringerMode);
Glenn Kastenba195eb2011-12-13 09:30:40 -0800861 }
Eric Laurent212532b2014-07-21 15:43:18 -0700862 if (mUseFixedVolume || isPlatformTelevision()) {
Eric Laurent83a017b2013-03-19 18:15:31 -0700863 ringerMode = AudioManager.RINGER_MODE_NORMAL;
864 }
Glenn Kastenba195eb2011-12-13 09:30:40 -0800865 synchronized(mSettingsLock) {
866 mRingerMode = ringerMode;
John Spurlock661f2cf2014-11-17 10:29:10 -0500867 if (mRingerModeExternal == -1) {
868 mRingerModeExternal = mRingerMode;
869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870
Eric Laurentdd45d012012-10-08 09:04:34 -0700871 // System.VIBRATE_ON is not used any more but defaults for mVibrateSetting
872 // are still needed while setVibrateSetting() and getVibrateSetting() are being
873 // deprecated.
John Spurlock61560172015-02-06 19:46:04 -0500874 mVibrateSetting = AudioSystem.getValueForVibrateSetting(0,
Eric Laurentdd45d012012-10-08 09:04:34 -0700875 AudioManager.VIBRATE_TYPE_NOTIFICATION,
876 mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT
877 : AudioManager.VIBRATE_SETTING_OFF);
John Spurlock61560172015-02-06 19:46:04 -0500878 mVibrateSetting = AudioSystem.getValueForVibrateSetting(mVibrateSetting,
Eric Laurentdd45d012012-10-08 09:04:34 -0700879 AudioManager.VIBRATE_TYPE_RINGER,
880 mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT
881 : AudioManager.VIBRATE_SETTING_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882
Eric Laurent24e0d9b2013-10-03 18:15:07 -0700883 updateRingerModeAffectedStreams();
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700884 readDockAudioSettings(cr);
Eric Laurent402f7f22011-02-04 12:30:32 -0800885 }
Eric Laurentc1d41662011-07-19 11:21:13 -0700886
Eric Laurentbc0fab1f2012-09-19 11:24:41 -0700887 mMuteAffectedStreams = System.getIntForUser(cr,
John Spurlock61560172015-02-06 19:46:04 -0500888 System.MUTE_STREAMS_AFFECTED, AudioSystem.DEFAULT_MUTE_STREAMS_AFFECTED,
John Spurlock24c05182015-02-05 12:30:36 -0500889 UserHandle.USER_CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890
Eric Laurentbc0fab1f2012-09-19 11:24:41 -0700891 boolean masterMute = System.getIntForUser(cr, System.VOLUME_MASTER_MUTE,
892 0, UserHandle.USER_CURRENT) == 1;
Eric Laurent83a017b2013-03-19 18:15:31 -0700893 if (mUseFixedVolume) {
894 masterMute = false;
895 AudioSystem.setMasterVolume(1.0f);
896 }
Justin Koh57978ed2012-04-03 17:37:58 -0700897 AudioSystem.setMasterMute(masterMute);
898 broadcastMasterMuteStatus(masterMute);
899
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400900 boolean microphoneMute =
901 System.getIntForUser(cr, System.MICROPHONE_MUTE, 0, UserHandle.USER_CURRENT) == 1;
902 AudioSystem.muteMicrophone(microphoneMute);
903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 // Each stream will read its own persisted settings
905
John Spurlockbcc10872014-11-28 15:29:21 -0500906 // Broadcast the sticky intents
907 broadcastRingerMode(AudioManager.RINGER_MODE_CHANGED_ACTION, mRingerModeExternal);
908 broadcastRingerMode(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION, mRingerMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909
910 // Broadcast vibrate settings
911 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
912 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
Jean-Michel Trivid589fea2011-04-15 11:28:10 -0700913
John Spurlock33f4e042014-07-11 13:10:58 -0400914 // Load settings for the volume controller
915 mVolumeController.loadSettings(cr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917
Eric Laurenta553c252009-07-17 12:17:14 -0700918 private int rescaleIndex(int index, int srcStream, int dstStream) {
919 return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921
Jon Eklund318f0fe2014-01-23 17:53:48 -0600922 private class AudioOrientationEventListener
923 extends OrientationEventListener {
924 public AudioOrientationEventListener(Context context) {
925 super(context);
926 }
927
928 @Override
929 public void onOrientationChanged(int orientation) {
930 //Even though we're responding to phone orientation events,
931 //use display rotation so audio stays in sync with video/dialogs
932 int newRotation = ((WindowManager) mContext.getSystemService(
933 Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
934 if (newRotation != mDeviceRotation) {
935 mDeviceRotation = newRotation;
936 setRotationForAudioSystem();
937 }
938 }
939 }
940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 ///////////////////////////////////////////////////////////////////////////
942 // IPC methods
943 ///////////////////////////////////////////////////////////////////////////
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 /** @see AudioManager#adjustVolume(int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700945 public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags,
946 String callingPackage) {
RoboErik272e1612014-09-05 11:39:29 -0700947 adjustSuggestedStreamVolume(direction, suggestedStreamType, flags, callingPackage,
948 Binder.getCallingUid());
949 }
950
951 private void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags,
952 String callingPackage, int uid) {
John Spurlockae641c92014-06-30 18:11:40 -0400953 if (DEBUG_VOL) Log.d(TAG, "adjustSuggestedStreamVolume() stream="+suggestedStreamType
954 + ", flags=" + flags);
Eric Laurent402f7f22011-02-04 12:30:32 -0800955 int streamType;
RoboErik4197cb62015-01-21 15:45:32 -0800956 boolean isMute = isMuteAdjust(direction);
Eric Laurent45c90ce2012-04-24 18:44:22 -0700957 if (mVolumeControlStream != -1) {
958 streamType = mVolumeControlStream;
Eric Laurent402f7f22011-02-04 12:30:32 -0800959 } else {
960 streamType = getActiveStreamType(suggestedStreamType);
961 }
John Spurlock33f4e042014-07-11 13:10:58 -0400962 final int resolvedStream = mStreamVolumeAlias[streamType];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963
RoboErik2811dd32014-08-12 09:48:13 -0700964 // Play sounds on STREAM_RING only.
965 if ((flags & AudioManager.FLAG_PLAY_SOUND) != 0 &&
John Spurlock33f4e042014-07-11 13:10:58 -0400966 resolvedStream != AudioSystem.STREAM_RING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 flags &= ~AudioManager.FLAG_PLAY_SOUND;
968 }
969
John Spurlock33f4e042014-07-11 13:10:58 -0400970 // For notifications/ring, show the ui before making any adjustments
RoboErik4197cb62015-01-21 15:45:32 -0800971 // Don't suppress mute/unmute requests
972 if (mVolumeController.suppressAdjustment(resolvedStream, flags, isMute)) {
John Spurlock33f4e042014-07-11 13:10:58 -0400973 direction = 0;
974 flags &= ~AudioManager.FLAG_PLAY_SOUND;
975 flags &= ~AudioManager.FLAG_VIBRATE;
976 if (DEBUG_VOL) Log.d(TAG, "Volume controller suppressed adjustment");
977 }
978
RoboErik272e1612014-09-05 11:39:29 -0700979 adjustStreamVolume(streamType, direction, flags, callingPackage, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981
982 /** @see AudioManager#adjustStreamVolume(int, int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700983 public void adjustStreamVolume(int streamType, int direction, int flags,
984 String callingPackage) {
RoboErik0dac35a2014-08-12 15:48:49 -0700985 adjustStreamVolume(streamType, direction, flags, callingPackage, Binder.getCallingUid());
986 }
987
988 private void adjustStreamVolume(int streamType, int direction, int flags,
989 String callingPackage, int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -0700990 if (mUseFixedVolume) {
991 return;
992 }
John Spurlockae641c92014-06-30 18:11:40 -0400993 if (DEBUG_VOL) Log.d(TAG, "adjustStreamVolume() stream="+streamType+", dir="+direction
994 + ", flags="+flags);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -0700995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 ensureValidDirection(direction);
997 ensureValidStreamType(streamType);
998
RoboErik4197cb62015-01-21 15:45:32 -0800999 boolean isMuteAdjust = isMuteAdjust(direction);
1000
Eric Laurent96a33d12011-11-08 10:31:57 -08001001 // use stream type alias here so that streams with same alias have the same behavior,
1002 // including with regard to silent mode control (e.g the use of STREAM_RING below and in
1003 // checkForRingerModeChange() in place of STREAM_RING or STREAM_NOTIFICATION)
Eric Laurent6d517662012-04-23 18:42:39 -07001004 int streamTypeAlias = mStreamVolumeAlias[streamType];
RoboErik4197cb62015-01-21 15:45:32 -08001005
1006 if (isMuteAdjust && !isStreamAffectedByMute(streamTypeAlias)) {
1007 return;
1008 }
1009
Eric Laurentb024c302011-10-14 17:19:27 -07001010 VolumeStreamState streamState = mStreamStates[streamTypeAlias];
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001011
1012 final int device = getDeviceForStream(streamTypeAlias);
Eric Laurent3ef75492012-11-28 12:12:23 -08001013
Eric Laurent42b041e2013-03-29 11:36:03 -07001014 int aliasIndex = streamState.getIndex(device);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 boolean adjustVolume = true;
Eric Laurent3ef75492012-11-28 12:12:23 -08001016 int step;
Eric Laurent24482012012-05-10 09:41:17 -07001017
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001018 // skip a2dp absolute volume control request when the device
1019 // is not an a2dp device
1020 if ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) == 0 &&
1021 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) != 0) {
1022 return;
1023 }
1024
RoboErik0dac35a2014-08-12 15:48:49 -07001025 if (mAppOps.noteOp(STEAM_VOLUME_OPS[streamTypeAlias], uid, callingPackage)
1026 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001027 return;
1028 }
1029
Eric Laurentfde16d52012-12-03 14:42:39 -08001030 // reset any pending volume command
1031 synchronized (mSafeMediaVolumeState) {
1032 mPendingVolumeCommand = null;
1033 }
1034
Eric Laurent3ef75492012-11-28 12:12:23 -08001035 flags &= ~AudioManager.FLAG_FIXED_VOLUME;
1036 if ((streamTypeAlias == AudioSystem.STREAM_MUSIC) &&
1037 ((device & mFixedVolumeDevices) != 0)) {
1038 flags |= AudioManager.FLAG_FIXED_VOLUME;
1039
1040 // Always toggle between max safe volume and 0 for fixed volume devices where safe
1041 // volume is enforced, and max and 0 for the others.
1042 // This is simulated by stepping by the full allowed volume range
1043 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE &&
1044 (device & mSafeMediaVolumeDevices) != 0) {
1045 step = mSafeMediaVolumeIndex;
1046 } else {
1047 step = streamState.getMaxIndex();
1048 }
1049 if (aliasIndex != 0) {
1050 aliasIndex = step;
1051 }
1052 } else {
1053 // convert one UI step (+/-1) into a number of internal units on the stream alias
1054 step = rescaleIndex(10, streamType, streamTypeAlias);
1055 }
1056
Eric Laurent42b041e2013-03-29 11:36:03 -07001057 // If either the client forces allowing ringer modes for this adjustment,
1058 // or the stream type is one that is affected by ringer modes
1059 if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
1060 (streamTypeAlias == getMasterStreamType())) {
John Spurlock661f2cf2014-11-17 10:29:10 -05001061 int ringerMode = getRingerModeInternal();
Eric Laurent42b041e2013-03-29 11:36:03 -07001062 // do not vibrate if already in vibrate mode
1063 if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
1064 flags &= ~AudioManager.FLAG_VIBRATE;
Eric Laurent3ef75492012-11-28 12:12:23 -08001065 }
RoboErik5452e252015-02-06 15:33:53 -08001066 // Check if the ringer mode handles this adjustment. If it does we don't
1067 // need to adjust the volume further.
1068 final int result = checkForRingerModeChange(aliasIndex, direction, step, streamState.mIsMuted);
John Spurlocka11b4af2014-06-01 11:52:23 -04001069 adjustVolume = (result & FLAG_ADJUST_VOLUME) != 0;
1070 // If suppressing a volume adjustment in silent mode, display the UI hint
1071 if ((result & AudioManager.FLAG_SHOW_SILENT_HINT) != 0) {
1072 flags |= AudioManager.FLAG_SHOW_SILENT_HINT;
1073 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001074 // If suppressing a volume down adjustment in vibrate mode, display the UI hint
1075 if ((result & AudioManager.FLAG_SHOW_VIBRATE_HINT) != 0) {
1076 flags |= AudioManager.FLAG_SHOW_VIBRATE_HINT;
1077 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001078 }
Eric Laurent3ef75492012-11-28 12:12:23 -08001079
Eric Laurent42b041e2013-03-29 11:36:03 -07001080 int oldIndex = mStreamStates[streamType].getIndex(device);
Eric Laurent3ef75492012-11-28 12:12:23 -08001081
Eric Laurent42b041e2013-03-29 11:36:03 -07001082 if (adjustVolume && (direction != AudioManager.ADJUST_SAME)) {
RoboErik5452e252015-02-06 15:33:53 -08001083 mAudioHandler.removeMessages(MSG_UNMUTE_STREAM);
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001084
John Du5a0cf7a2013-07-19 11:30:34 -07001085 // Check if volume update should be send to AVRCP
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001086 if (streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1087 (device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
1088 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) {
1089 synchronized (mA2dpAvrcpLock) {
1090 if (mA2dp != null && mAvrcpAbsVolSupported) {
1091 mA2dp.adjustAvrcpAbsoluteVolume(direction);
1092 }
John Du5a0cf7a2013-07-19 11:30:34 -07001093 }
1094 }
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001095
RoboErik4197cb62015-01-21 15:45:32 -08001096 if (isMuteAdjust) {
1097 boolean state;
1098 if (direction == AudioManager.ADJUST_TOGGLE_MUTE) {
1099 state = !streamState.mIsMuted;
1100 } else {
1101 state = direction == AudioManager.ADJUST_MUTE;
1102 }
1103 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1104 setSystemAudioMute(state);
1105 }
1106 for (int stream = 0; stream < mStreamStates.length; stream++) {
1107 if (streamTypeAlias == mStreamVolumeAlias[stream]) {
1108 mStreamStates[stream].mute(state);
1109
1110 Intent intent = new Intent(AudioManager.STREAM_MUTE_CHANGED_ACTION);
1111 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, stream);
1112 intent.putExtra(AudioManager.EXTRA_STREAM_VOLUME_MUTED, state);
1113 sendBroadcastToAll(intent);
1114 }
1115 }
1116 } else if ((direction == AudioManager.ADJUST_RAISE) &&
Eric Laurent42b041e2013-03-29 11:36:03 -07001117 !checkSafeMediaVolume(streamTypeAlias, aliasIndex + step, device)) {
RoboErik4197cb62015-01-21 15:45:32 -08001118 Log.e(TAG, "adjustStreamVolume() safe volume index = " + oldIndex);
John Spurlock3346a802014-05-20 16:25:37 -04001119 mVolumeController.postDisplaySafeVolumeWarning(flags);
RoboErik4197cb62015-01-21 15:45:32 -08001120 } else if (streamState.adjustIndex(direction * step, device) || streamState.mIsMuted) {
1121 // Post message to set system volume (it in turn will post a
1122 // message to persist).
1123 if (streamState.mIsMuted) {
1124 // Unmute the stream if it was previously muted
RoboErik5452e252015-02-06 15:33:53 -08001125 if (direction == AudioManager.ADJUST_RAISE) {
1126 // unmute immediately for volume up
1127 streamState.mute(false);
1128 } else if (direction == AudioManager.ADJUST_LOWER) {
1129 sendMsg(mAudioHandler, MSG_UNMUTE_STREAM, SENDMSG_QUEUE,
1130 streamTypeAlias, flags, null, UNMUTE_STREAM_DELAY);
1131 }
RoboErik4197cb62015-01-21 15:45:32 -08001132 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001133 sendMsg(mAudioHandler,
1134 MSG_SET_DEVICE_VOLUME,
1135 SENDMSG_QUEUE,
1136 device,
1137 0,
1138 streamState,
1139 0);
Eric Laurent4bbcc652012-09-24 14:26:30 -07001140 }
Jungshik Jang41d97462014-06-30 22:26:29 +09001141
RoboErik4197cb62015-01-21 15:45:32 -08001142 // Check if volume update should be sent to Hdmi system audio.
Jungshik Jang41d97462014-06-30 22:26:29 +09001143 int newIndex = mStreamStates[streamType].getIndex(device);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001144 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1145 setSystemAudioVolume(oldIndex, newIndex, getStreamMaxVolume(streamType), flags);
1146 }
Eric Laurent212532b2014-07-21 15:43:18 -07001147 if (mHdmiManager != null) {
1148 synchronized (mHdmiManager) {
Eric Laurent212532b2014-07-21 15:43:18 -07001149 // mHdmiCecSink true => mHdmiPlaybackClient != null
1150 if (mHdmiCecSink &&
1151 streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1152 oldIndex != newIndex) {
1153 synchronized (mHdmiPlaybackClient) {
1154 int keyCode = (direction == -1) ? KeyEvent.KEYCODE_VOLUME_DOWN :
RoboErik4197cb62015-01-21 15:45:32 -08001155 KeyEvent.KEYCODE_VOLUME_UP;
Eric Laurent212532b2014-07-21 15:43:18 -07001156 mHdmiPlaybackClient.sendKeyEvent(keyCode, true);
1157 mHdmiPlaybackClient.sendKeyEvent(keyCode, false);
1158 }
Jungshik Jang41d97462014-06-30 22:26:29 +09001159 }
1160 }
1161 }
Eric Laurent4bbcc652012-09-24 14:26:30 -07001162 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001163 int index = mStreamStates[streamType].getIndex(device);
Eric Laurent25101b02011-02-02 09:33:30 -08001164 sendVolumeUpdate(streamType, oldIndex, index, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
RoboErik5452e252015-02-06 15:33:53 -08001167 // Called after a delay when volume down is pressed while muted
1168 private void onUnmuteStream(int stream, int flags) {
1169 VolumeStreamState streamState = mStreamStates[stream];
1170 streamState.mute(false);
1171
1172 final int device = getDeviceForStream(stream);
1173 final int index = mStreamStates[stream].getIndex(device);
1174 sendVolumeUpdate(stream, index, index, flags);
1175 }
1176
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001177 private void setSystemAudioVolume(int oldVolume, int newVolume, int maxVolume, int flags) {
1178 if (mHdmiManager == null
1179 || mHdmiTvClient == null
1180 || oldVolume == newVolume
1181 || (flags & AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME) != 0) return;
1182
1183 // Sets the audio volume of AVR when we are in system audio mode. The new volume info
1184 // is tranformed to HDMI-CEC commands and passed through CEC bus.
1185 synchronized (mHdmiManager) {
1186 if (!mHdmiSystemAudioSupported) return;
1187 synchronized (mHdmiTvClient) {
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001188 final long token = Binder.clearCallingIdentity();
1189 try {
1190 mHdmiTvClient.setSystemAudioVolume(
1191 (oldVolume + 5) / 10, (newVolume + 5) / 10, maxVolume);
1192 } finally {
1193 Binder.restoreCallingIdentity(token);
1194 }
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001195 }
1196 }
1197 }
1198
Dianne Hackborn961cae92013-03-20 14:59:43 -07001199 /** @see AudioManager#adjustMasterVolume(int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001200 public void adjustMasterVolume(int steps, int flags, String callingPackage) {
RoboErik519c7742014-11-18 10:59:09 -08001201 adjustMasterVolume(steps, flags, callingPackage, Binder.getCallingUid());
1202 }
1203
1204 public void adjustMasterVolume(int steps, int flags, String callingPackage, int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001205 if (mUseFixedVolume) {
1206 return;
1207 }
RoboErik4197cb62015-01-21 15:45:32 -08001208 if (isMuteAdjust(steps)) {
1209 setMasterMuteInternal(steps, flags, callingPackage, uid);
1210 return;
1211 }
Lei Zhang6c798972012-03-02 11:40:12 -08001212 ensureValidSteps(steps);
Mike Lockwood97606472012-02-09 11:24:10 -08001213 int volume = Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME);
1214 int delta = 0;
Lei Zhang6c798972012-03-02 11:40:12 -08001215 int numSteps = Math.abs(steps);
1216 int direction = steps > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER;
1217 for (int i = 0; i < numSteps; ++i) {
1218 delta = findVolumeDelta(direction, volume);
1219 volume += delta;
Mike Lockwoodcbdb49d2011-10-20 12:54:05 -04001220 }
RoboErik24b082f2012-02-24 14:21:16 -08001221
Lei Zhang6c798972012-03-02 11:40:12 -08001222 //Log.d(TAG, "adjustMasterVolume volume: " + volume + " steps: " + steps);
RoboErik519c7742014-11-18 10:59:09 -08001223 setMasterVolume(volume, flags, callingPackage, uid);
Mike Lockwoodcbdb49d2011-10-20 12:54:05 -04001224 }
1225
Eric Laurentfde16d52012-12-03 14:42:39 -08001226 // StreamVolumeCommand contains the information needed to defer the process of
1227 // setStreamVolume() in case the user has to acknowledge the safe volume warning message.
1228 class StreamVolumeCommand {
1229 public final int mStreamType;
1230 public final int mIndex;
1231 public final int mFlags;
1232 public final int mDevice;
Eric Laurent9ce379a2010-02-16 06:00:26 -08001233
Eric Laurentfde16d52012-12-03 14:42:39 -08001234 StreamVolumeCommand(int streamType, int index, int flags, int device) {
1235 mStreamType = streamType;
1236 mIndex = index;
1237 mFlags = flags;
1238 mDevice = device;
Eric Laurentb024c302011-10-14 17:19:27 -07001239 }
John Spurlock35134602014-07-24 18:10:48 -04001240
1241 @Override
1242 public String toString() {
1243 return new StringBuilder().append("{streamType=").append(mStreamType).append(",index=")
1244 .append(mIndex).append(",flags=").append(mFlags).append(",device=")
1245 .append(mDevice).append('}').toString();
1246 }
Eric Laurentfde16d52012-12-03 14:42:39 -08001247 };
Eric Laurent3ef75492012-11-28 12:12:23 -08001248
Eric Laurentfde16d52012-12-03 14:42:39 -08001249 private void onSetStreamVolume(int streamType, int index, int flags, int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07001250 setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, false);
Eric Laurent3ef75492012-11-28 12:12:23 -08001251 // setting volume on master stream type also controls silent mode
1252 if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
1253 (mStreamVolumeAlias[streamType] == getMasterStreamType())) {
1254 int newRingerMode;
1255 if (index == 0) {
1256 newRingerMode = mHasVibrator ? AudioManager.RINGER_MODE_VIBRATE
John Spurlock86005342014-05-23 11:58:00 -04001257 : VOLUME_SETS_RINGER_MODE_SILENT ? AudioManager.RINGER_MODE_SILENT
1258 : AudioManager.RINGER_MODE_NORMAL;
Eric Laurent3ef75492012-11-28 12:12:23 -08001259 } else {
1260 newRingerMode = AudioManager.RINGER_MODE_NORMAL;
1261 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001262 setRingerMode(newRingerMode, TAG + ".onSetStreamVolume", false /*external*/);
Eric Laurent3ef75492012-11-28 12:12:23 -08001263 }
Eric Laurentfde16d52012-12-03 14:42:39 -08001264 }
1265
1266 /** @see AudioManager#setStreamVolume(int, int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001267 public void setStreamVolume(int streamType, int index, int flags, String callingPackage) {
RoboErik0dac35a2014-08-12 15:48:49 -07001268 setStreamVolume(streamType, index, flags, callingPackage, Binder.getCallingUid());
1269 }
1270
1271 private void setStreamVolume(int streamType, int index, int flags, String callingPackage,
1272 int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001273 if (mUseFixedVolume) {
1274 return;
1275 }
1276
Eric Laurentfde16d52012-12-03 14:42:39 -08001277 ensureValidStreamType(streamType);
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001278 int streamTypeAlias = mStreamVolumeAlias[streamType];
1279 VolumeStreamState streamState = mStreamStates[streamTypeAlias];
Eric Laurentfde16d52012-12-03 14:42:39 -08001280
1281 final int device = getDeviceForStream(streamType);
1282 int oldIndex;
1283
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001284 // skip a2dp absolute volume control request when the device
1285 // is not an a2dp device
1286 if ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) == 0 &&
1287 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) != 0) {
1288 return;
1289 }
1290
RoboErik0dac35a2014-08-12 15:48:49 -07001291 if (mAppOps.noteOp(STEAM_VOLUME_OPS[streamTypeAlias], uid, callingPackage)
1292 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001293 return;
1294 }
1295
Eric Laurentfde16d52012-12-03 14:42:39 -08001296 synchronized (mSafeMediaVolumeState) {
1297 // reset any pending volume command
1298 mPendingVolumeCommand = null;
1299
Eric Laurent42b041e2013-03-29 11:36:03 -07001300 oldIndex = streamState.getIndex(device);
Eric Laurentfde16d52012-12-03 14:42:39 -08001301
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001302 index = rescaleIndex(index * 10, streamType, streamTypeAlias);
Eric Laurentfde16d52012-12-03 14:42:39 -08001303
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001304 if (streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1305 (device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
1306 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) {
1307 synchronized (mA2dpAvrcpLock) {
1308 if (mA2dp != null && mAvrcpAbsVolSupported) {
Zhihai Xu2f4a2b12014-01-10 16:44:39 -08001309 mA2dp.setAvrcpAbsoluteVolume(index / 10);
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001310 }
John Du5a0cf7a2013-07-19 11:30:34 -07001311 }
1312 }
1313
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001314 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1315 setSystemAudioVolume(oldIndex, index, getStreamMaxVolume(streamType), flags);
Jungshik Jang41d97462014-06-30 22:26:29 +09001316 }
1317
Eric Laurentfde16d52012-12-03 14:42:39 -08001318 flags &= ~AudioManager.FLAG_FIXED_VOLUME;
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001319 if ((streamTypeAlias == AudioSystem.STREAM_MUSIC) &&
Eric Laurentfde16d52012-12-03 14:42:39 -08001320 ((device & mFixedVolumeDevices) != 0)) {
1321 flags |= AudioManager.FLAG_FIXED_VOLUME;
1322
1323 // volume is either 0 or max allowed for fixed volume devices
1324 if (index != 0) {
1325 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE &&
1326 (device & mSafeMediaVolumeDevices) != 0) {
1327 index = mSafeMediaVolumeIndex;
1328 } else {
1329 index = streamState.getMaxIndex();
1330 }
1331 }
1332 }
1333
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001334 if (!checkSafeMediaVolume(streamTypeAlias, index, device)) {
John Spurlock3346a802014-05-20 16:25:37 -04001335 mVolumeController.postDisplaySafeVolumeWarning(flags);
Eric Laurentfde16d52012-12-03 14:42:39 -08001336 mPendingVolumeCommand = new StreamVolumeCommand(
1337 streamType, index, flags, device);
1338 } else {
1339 onSetStreamVolume(streamType, index, flags, device);
Eric Laurent42b041e2013-03-29 11:36:03 -07001340 index = mStreamStates[streamType].getIndex(device);
Eric Laurentfde16d52012-12-03 14:42:39 -08001341 }
1342 }
Eric Laurent25101b02011-02-02 09:33:30 -08001343 sendVolumeUpdate(streamType, oldIndex, index, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
1345
Eric Laurent45c90ce2012-04-24 18:44:22 -07001346 /** @see AudioManager#forceVolumeControlStream(int) */
1347 public void forceVolumeControlStream(int streamType, IBinder cb) {
1348 synchronized(mForceControlStreamLock) {
1349 mVolumeControlStream = streamType;
1350 if (mVolumeControlStream == -1) {
1351 if (mForceControlStreamClient != null) {
1352 mForceControlStreamClient.release();
1353 mForceControlStreamClient = null;
1354 }
1355 } else {
1356 mForceControlStreamClient = new ForceControlStreamClient(cb);
1357 }
1358 }
1359 }
1360
1361 private class ForceControlStreamClient implements IBinder.DeathRecipient {
1362 private IBinder mCb; // To be notified of client's death
1363
1364 ForceControlStreamClient(IBinder cb) {
1365 if (cb != null) {
1366 try {
1367 cb.linkToDeath(this, 0);
1368 } catch (RemoteException e) {
1369 // Client has died!
1370 Log.w(TAG, "ForceControlStreamClient() could not link to "+cb+" binder death");
1371 cb = null;
1372 }
1373 }
1374 mCb = cb;
1375 }
1376
1377 public void binderDied() {
1378 synchronized(mForceControlStreamLock) {
1379 Log.w(TAG, "SCO client died");
1380 if (mForceControlStreamClient != this) {
1381 Log.w(TAG, "unregistered control stream client died");
1382 } else {
1383 mForceControlStreamClient = null;
1384 mVolumeControlStream = -1;
1385 }
1386 }
1387 }
1388
1389 public void release() {
1390 if (mCb != null) {
1391 mCb.unlinkToDeath(this, 0);
1392 mCb = null;
1393 }
1394 }
1395 }
1396
Lei Zhang6c798972012-03-02 11:40:12 -08001397 private int findVolumeDelta(int direction, int volume) {
1398 int delta = 0;
1399 if (direction == AudioManager.ADJUST_RAISE) {
1400 if (volume == MAX_MASTER_VOLUME) {
1401 return 0;
1402 }
1403 // This is the default value if we make it to the end
1404 delta = mMasterVolumeRamp[1];
1405 // If we're raising the volume move down the ramp array until we
1406 // find the volume we're above and use that groups delta.
1407 for (int i = mMasterVolumeRamp.length - 1; i > 1; i -= 2) {
1408 if (volume >= mMasterVolumeRamp[i - 1]) {
1409 delta = mMasterVolumeRamp[i];
1410 break;
1411 }
1412 }
1413 } else if (direction == AudioManager.ADJUST_LOWER){
1414 if (volume == 0) {
1415 return 0;
1416 }
1417 int length = mMasterVolumeRamp.length;
1418 // This is the default value if we make it to the end
1419 delta = -mMasterVolumeRamp[length - 1];
1420 // If we're lowering the volume move up the ramp array until we
1421 // find the volume we're below and use the group below it's delta
1422 for (int i = 2; i < length; i += 2) {
1423 if (volume <= mMasterVolumeRamp[i]) {
1424 delta = -mMasterVolumeRamp[i - 1];
1425 break;
1426 }
1427 }
1428 }
1429 return delta;
1430 }
1431
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001432 private void sendBroadcastToAll(Intent intent) {
Christopher Tate267603f2015-01-20 14:21:21 -08001433 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001434 final long ident = Binder.clearCallingIdentity();
1435 try {
1436 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1437 } finally {
1438 Binder.restoreCallingIdentity(ident);
1439 }
1440 }
1441
1442 private void sendStickyBroadcastToAll(Intent intent) {
1443 final long ident = Binder.clearCallingIdentity();
1444 try {
1445 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1446 } finally {
1447 Binder.restoreCallingIdentity(ident);
1448 }
1449 }
1450
Eric Laurent25101b02011-02-02 09:33:30 -08001451 // UI update and Broadcast Intent
1452 private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) {
Eric Laurent212532b2014-07-21 15:43:18 -07001453 if (!isPlatformVoice() && (streamType == AudioSystem.STREAM_RING)) {
Eric Laurent25101b02011-02-02 09:33:30 -08001454 streamType = AudioSystem.STREAM_NOTIFICATION;
1455 }
1456
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001457 if (streamType == AudioSystem.STREAM_MUSIC) {
1458 flags = updateFlagsForSystemAudio(flags);
Jungshik Jang1a6be6e2014-09-16 11:04:54 +09001459 }
John Spurlock3346a802014-05-20 16:25:37 -04001460 mVolumeController.postVolumeChanged(streamType, flags);
Eric Laurent25101b02011-02-02 09:33:30 -08001461
Eric Laurent4bbcc652012-09-24 14:26:30 -07001462 if ((flags & AudioManager.FLAG_FIXED_VOLUME) == 0) {
1463 oldIndex = (oldIndex + 5) / 10;
1464 index = (index + 5) / 10;
1465 Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
1466 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType);
1467 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
1468 intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
1469 sendBroadcastToAll(intent);
1470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
1472
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001473 // If Hdmi-CEC system audio mode is on, we show volume bar only when TV
1474 // receives volume notification from Audio Receiver.
1475 private int updateFlagsForSystemAudio(int flags) {
1476 if (mHdmiTvClient != null) {
1477 synchronized (mHdmiTvClient) {
1478 if (mHdmiSystemAudioSupported &&
1479 ((flags & AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME) == 0)) {
1480 flags &= ~AudioManager.FLAG_SHOW_UI;
1481 }
1482 }
1483 }
1484 return flags;
1485 }
1486
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001487 // UI update and Broadcast Intent
1488 private void sendMasterVolumeUpdate(int flags, int oldVolume, int newVolume) {
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001489 mVolumeController.postMasterVolumeChanged(updateFlagsForSystemAudio(flags));
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001490
1491 Intent intent = new Intent(AudioManager.MASTER_VOLUME_CHANGED_ACTION);
1492 intent.putExtra(AudioManager.EXTRA_PREV_MASTER_VOLUME_VALUE, oldVolume);
1493 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_VALUE, newVolume);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001494 sendBroadcastToAll(intent);
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001495 }
1496
1497 // UI update and Broadcast Intent
1498 private void sendMasterMuteUpdate(boolean muted, int flags) {
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001499 mVolumeController.postMasterMuteChanged(updateFlagsForSystemAudio(flags));
Justin Koh57978ed2012-04-03 17:37:58 -07001500 broadcastMasterMuteStatus(muted);
1501 }
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001502
Justin Koh57978ed2012-04-03 17:37:58 -07001503 private void broadcastMasterMuteStatus(boolean muted) {
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001504 Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
1505 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, muted);
Justin Koh57978ed2012-04-03 17:37:58 -07001506 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1507 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001508 sendStickyBroadcastToAll(intent);
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001509 }
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 * Sets the stream state's index, and posts a message to set system volume.
1513 * This will not call out to the UI. Assumes a valid stream type.
1514 *
1515 * @param streamType Type of the stream
1516 * @param index Desired volume index of the stream
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001517 * @param device the device whose volume must be changed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 * @param force If true, set the volume even if the desired volume is same
1519 * as the current volume.
1520 */
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001521 private void setStreamVolumeInt(int streamType,
1522 int index,
1523 int device,
Eric Laurent42b041e2013-03-29 11:36:03 -07001524 boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurent5b4e6542010-03-19 20:02:21 -07001526
Eric Laurent42b041e2013-03-29 11:36:03 -07001527 if (streamState.setIndex(index, device) || force) {
1528 // Post message to set system volume (it in turn will post a message
1529 // to persist).
1530 sendMsg(mAudioHandler,
1531 MSG_SET_DEVICE_VOLUME,
1532 SENDMSG_QUEUE,
1533 device,
1534 0,
1535 streamState,
1536 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 }
1539
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001540 private void setSystemAudioMute(boolean state) {
1541 if (mHdmiManager == null || mHdmiTvClient == null) return;
1542 synchronized (mHdmiManager) {
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001543 if (!mHdmiSystemAudioSupported) return;
1544 synchronized (mHdmiTvClient) {
1545 final long token = Binder.clearCallingIdentity();
1546 try {
1547 mHdmiTvClient.setSystemAudioMute(state);
1548 } finally {
1549 Binder.restoreCallingIdentity(token);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001550 }
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001551 }
1552 }
1553 }
1554
Eric Laurent25101b02011-02-02 09:33:30 -08001555 /** get stream mute state. */
1556 public boolean isStreamMute(int streamType) {
RoboErik7c82ced2014-12-04 17:39:08 -08001557 if (streamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1558 streamType = getActiveStreamType(streamType);
1559 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001560 synchronized (VolumeStreamState.class) {
RoboErik4197cb62015-01-21 15:45:32 -08001561 return mStreamStates[streamType].mIsMuted;
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001562 }
Eric Laurent25101b02011-02-02 09:33:30 -08001563 }
1564
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07001565 private class RmtSbmxFullVolDeathHandler implements IBinder.DeathRecipient {
1566 private IBinder mICallback; // To be notified of client's death
1567
1568 RmtSbmxFullVolDeathHandler(IBinder cb) {
1569 mICallback = cb;
1570 try {
1571 cb.linkToDeath(this, 0/*flags*/);
1572 } catch (RemoteException e) {
1573 Log.e(TAG, "can't link to death", e);
1574 }
1575 }
1576
1577 boolean isHandlerFor(IBinder cb) {
1578 return mICallback.equals(cb);
1579 }
1580
1581 void forget() {
1582 try {
1583 mICallback.unlinkToDeath(this, 0/*flags*/);
1584 } catch (NoSuchElementException e) {
1585 Log.e(TAG, "error unlinking to death", e);
1586 }
1587 }
1588
1589 public void binderDied() {
1590 Log.w(TAG, "Recorder with remote submix at full volume died " + mICallback);
1591 forceRemoteSubmixFullVolume(false, mICallback);
1592 }
1593 }
1594
1595 /**
1596 * call must be synchronized on mRmtSbmxFullVolDeathHandlers
1597 * @return true if there is a registered death handler, false otherwise */
1598 private boolean discardRmtSbmxFullVolDeathHandlerFor(IBinder cb) {
1599 Iterator<RmtSbmxFullVolDeathHandler> it = mRmtSbmxFullVolDeathHandlers.iterator();
1600 while (it.hasNext()) {
1601 final RmtSbmxFullVolDeathHandler handler = it.next();
1602 if (handler.isHandlerFor(cb)) {
1603 handler.forget();
1604 mRmtSbmxFullVolDeathHandlers.remove(handler);
1605 return true;
1606 }
1607 }
1608 return false;
1609 }
1610
1611 /** call synchronized on mRmtSbmxFullVolDeathHandlers */
1612 private boolean hasRmtSbmxFullVolDeathHandlerFor(IBinder cb) {
1613 Iterator<RmtSbmxFullVolDeathHandler> it = mRmtSbmxFullVolDeathHandlers.iterator();
1614 while (it.hasNext()) {
1615 if (it.next().isHandlerFor(cb)) {
1616 return true;
1617 }
1618 }
1619 return false;
1620 }
1621
1622 private int mRmtSbmxFullVolRefCount = 0;
1623 private ArrayList<RmtSbmxFullVolDeathHandler> mRmtSbmxFullVolDeathHandlers =
1624 new ArrayList<RmtSbmxFullVolDeathHandler>();
1625
1626 public void forceRemoteSubmixFullVolume(boolean startForcing, IBinder cb) {
1627 if (cb == null) {
1628 return;
1629 }
1630 if ((PackageManager.PERMISSION_GRANTED != mContext.checkCallingOrSelfPermission(
1631 android.Manifest.permission.CAPTURE_AUDIO_OUTPUT))) {
1632 Log.w(TAG, "Trying to call forceRemoteSubmixFullVolume() without CAPTURE_AUDIO_OUTPUT");
1633 return;
1634 }
1635 synchronized(mRmtSbmxFullVolDeathHandlers) {
1636 boolean applyRequired = false;
1637 if (startForcing) {
1638 if (!hasRmtSbmxFullVolDeathHandlerFor(cb)) {
1639 mRmtSbmxFullVolDeathHandlers.add(new RmtSbmxFullVolDeathHandler(cb));
1640 if (mRmtSbmxFullVolRefCount == 0) {
1641 mFullVolumeDevices |= AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1642 mFixedVolumeDevices |= AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1643 applyRequired = true;
1644 }
1645 mRmtSbmxFullVolRefCount++;
1646 }
1647 } else {
1648 if (discardRmtSbmxFullVolDeathHandlerFor(cb) && (mRmtSbmxFullVolRefCount > 0)) {
1649 mRmtSbmxFullVolRefCount--;
1650 if (mRmtSbmxFullVolRefCount == 0) {
1651 mFullVolumeDevices &= ~AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1652 mFixedVolumeDevices &= ~AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1653 applyRequired = true;
1654 }
1655 }
1656 }
1657 if (applyRequired) {
1658 // Assumes only STREAM_MUSIC going through DEVICE_OUT_REMOTE_SUBMIX
1659 checkAllFixedVolumeDevices(AudioSystem.STREAM_MUSIC);
1660 mStreamStates[AudioSystem.STREAM_MUSIC].applyAllVolumes();
1661 }
1662 }
1663 }
1664
RoboErik4197cb62015-01-21 15:45:32 -08001665 private void setMasterMuteInternal(int adjust, int flags, String callingPackage, int uid) {
RoboErik7c82ced2014-12-04 17:39:08 -08001666 if (mAppOps.noteOp(AppOpsManager.OP_AUDIO_MASTER_VOLUME, uid, callingPackage)
1667 != AppOpsManager.MODE_ALLOWED) {
Julia Reynolds4a21b252014-06-04 11:11:43 -04001668 return;
1669 }
RoboErik4197cb62015-01-21 15:45:32 -08001670 boolean state;
1671 if (adjust == AudioManager.ADJUST_TOGGLE_MUTE) {
1672 state = !AudioSystem.getMasterMute();
1673 } else {
1674 state = adjust == AudioManager.ADJUST_MUTE;
1675 }
Jason Simmons1ce5b262012-02-02 13:00:17 -08001676 if (state != AudioSystem.getMasterMute()) {
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001677 setSystemAudioMute(state);
Jason Simmons1ce5b262012-02-02 13:00:17 -08001678 AudioSystem.setMasterMute(state);
Justin Koh57978ed2012-04-03 17:37:58 -07001679 // Post a persist master volume msg
Justin Koh75cf9e12012-04-04 15:27:37 -07001680 sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME_MUTE, SENDMSG_REPLACE, state ? 1
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001681 : 0, UserHandle.getCallingUserId(), null, PERSIST_DELAY);
Justin Koh0273af52012-04-04 18:29:50 -07001682 sendMasterMuteUpdate(state, flags);
RoboErik7c82ced2014-12-04 17:39:08 -08001683
1684 Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
1685 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, state);
1686 sendBroadcastToAll(intent);
Jason Simmons1ce5b262012-02-02 13:00:17 -08001687 }
Mike Lockwoodce952c82011-11-14 10:47:42 -08001688 }
1689
1690 /** get master mute state. */
1691 public boolean isMasterMute() {
Mike Lockwood3194ea92011-12-07 11:47:31 -08001692 return AudioSystem.getMasterMute();
Mike Lockwoodce952c82011-11-14 10:47:42 -08001693 }
1694
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07001695 protected static int getMaxStreamVolume(int streamType) {
1696 return MAX_STREAM_VOLUME[streamType];
1697 }
1698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 /** @see AudioManager#getStreamVolume(int) */
1700 public int getStreamVolume(int streamType) {
1701 ensureValidStreamType(streamType);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001702 int device = getDeviceForStream(streamType);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001703 synchronized (VolumeStreamState.class) {
1704 int index = mStreamStates[streamType].getIndex(device);
Eric Laurent4bbcc652012-09-24 14:26:30 -07001705
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001706 // by convention getStreamVolume() returns 0 when a stream is muted.
RoboErik4197cb62015-01-21 15:45:32 -08001707 if (mStreamStates[streamType].mIsMuted) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001708 index = 0;
1709 }
1710 if (index != 0 && (mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) &&
1711 (device & mFixedVolumeDevices) != 0) {
1712 index = mStreamStates[streamType].getMaxIndex();
1713 }
1714 return (index + 5) / 10;
Eric Laurent42b041e2013-03-29 11:36:03 -07001715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
1717
RoboErik519c7742014-11-18 10:59:09 -08001718 @Override
Mike Lockwood47676902011-11-08 10:31:21 -08001719 public int getMasterVolume() {
Mike Lockwoodce952c82011-11-14 10:47:42 -08001720 if (isMasterMute()) return 0;
1721 return getLastAudibleMasterVolume();
Mike Lockwood8dc1dab2011-10-27 09:52:41 -04001722 }
1723
RoboErik519c7742014-11-18 10:59:09 -08001724 @Override
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001725 public void setMasterVolume(int volume, int flags, String callingPackage) {
RoboErik519c7742014-11-18 10:59:09 -08001726 setMasterVolume(volume, flags, callingPackage, Binder.getCallingUid());
1727 }
1728
1729 public void setMasterVolume(int volume, int flags, String callingPackage, int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001730 if (mUseFixedVolume) {
1731 return;
1732 }
1733
RoboErik519c7742014-11-18 10:59:09 -08001734 if (mAppOps.noteOp(AppOpsManager.OP_AUDIO_MASTER_VOLUME, uid, callingPackage)
1735 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001736 return;
1737 }
1738
Mike Lockwood97606472012-02-09 11:24:10 -08001739 if (volume < 0) {
1740 volume = 0;
1741 } else if (volume > MAX_MASTER_VOLUME) {
1742 volume = MAX_MASTER_VOLUME;
1743 }
Mike Lockwood5c55a052011-12-15 17:21:44 -05001744 doSetMasterVolume((float)volume / MAX_MASTER_VOLUME, flags);
1745 }
1746
1747 private void doSetMasterVolume(float volume, int flags) {
1748 // don't allow changing master volume when muted
1749 if (!AudioSystem.getMasterMute()) {
1750 int oldVolume = getMasterVolume();
1751 AudioSystem.setMasterVolume(volume);
1752
1753 int newVolume = getMasterVolume();
1754 if (newVolume != oldVolume) {
1755 // Post a persist master volume msg
1756 sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME, SENDMSG_REPLACE,
1757 Math.round(volume * (float)1000.0), 0, null, PERSIST_DELAY);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001758 setSystemAudioVolume(oldVolume, newVolume, getMasterMaxVolume(), flags);
Mike Lockwood5c55a052011-12-15 17:21:44 -05001759 }
Justin Koh3caba512012-04-02 15:32:18 -07001760 // Send the volume update regardless whether there was a change.
1761 sendMasterVolumeUpdate(flags, oldVolume, newVolume);
Mike Lockwood5c55a052011-12-15 17:21:44 -05001762 }
Mike Lockwood8dc1dab2011-10-27 09:52:41 -04001763 }
1764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 /** @see AudioManager#getStreamMaxVolume(int) */
1766 public int getStreamMaxVolume(int streamType) {
1767 ensureValidStreamType(streamType);
Eric Laurenta553c252009-07-17 12:17:14 -07001768 return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770
Mike Lockwood47676902011-11-08 10:31:21 -08001771 public int getMasterMaxVolume() {
1772 return MAX_MASTER_VOLUME;
1773 }
Eric Laurent25101b02011-02-02 09:33:30 -08001774
1775 /** Get last audible volume before stream was muted. */
1776 public int getLastAudibleStreamVolume(int streamType) {
1777 ensureValidStreamType(streamType);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001778 int device = getDeviceForStream(streamType);
Eric Laurent42b041e2013-03-29 11:36:03 -07001779 return (mStreamStates[streamType].getIndex(device) + 5) / 10;
Eric Laurent25101b02011-02-02 09:33:30 -08001780 }
1781
Mike Lockwoodce952c82011-11-14 10:47:42 -08001782 /** Get last audible master volume before it was muted. */
1783 public int getLastAudibleMasterVolume() {
1784 return Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME);
1785 }
1786
Dianne Hackborn961cae92013-03-20 14:59:43 -07001787 /** @see AudioManager#getMasterStreamType() */
Eric Laurent6d517662012-04-23 18:42:39 -07001788 public int getMasterStreamType() {
John Spurlock4f0f1202014-08-05 13:28:33 -04001789 return mStreamVolumeAlias[AudioSystem.STREAM_SYSTEM];
Eric Laurent6d517662012-04-23 18:42:39 -07001790 }
1791
Emily Bernier22c921a2014-05-28 11:01:32 -04001792 /** @see AudioManager#setMicrophoneMute(boolean) */
1793 public void setMicrophoneMute(boolean on, String callingPackage) {
1794 if (mAppOps.noteOp(AppOpsManager.OP_MUTE_MICROPHONE, Binder.getCallingUid(),
1795 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1796 return;
1797 }
Jean-Michel Trivi4a4fea02014-08-29 18:14:09 -07001798 if (!checkAudioSettingsPermission("setMicrophoneMute()")) {
1799 return;
1800 }
Emily Bernier22c921a2014-05-28 11:01:32 -04001801
1802 AudioSystem.muteMicrophone(on);
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001803 // Post a persist microphone msg.
1804 sendMsg(mAudioHandler, MSG_PERSIST_MICROPHONE_MUTE, SENDMSG_REPLACE, on ? 1
1805 : 0, UserHandle.getCallingUserId(), null, PERSIST_DELAY);
Emily Bernier22c921a2014-05-28 11:01:32 -04001806 }
1807
John Spurlock661f2cf2014-11-17 10:29:10 -05001808 @Override
1809 public int getRingerModeExternal() {
1810 synchronized(mSettingsLock) {
1811 return mRingerModeExternal;
1812 }
1813 }
1814
1815 @Override
1816 public int getRingerModeInternal() {
Glenn Kastenba195eb2011-12-13 09:30:40 -08001817 synchronized(mSettingsLock) {
1818 return mRingerMode;
1819 }
1820 }
1821
1822 private void ensureValidRingerMode(int ringerMode) {
John Spurlock97559372014-10-24 16:27:36 -04001823 if (!isValidRingerMode(ringerMode)) {
Glenn Kastenba195eb2011-12-13 09:30:40 -08001824 throw new IllegalArgumentException("Bad ringer mode " + ringerMode);
1825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827
John Spurlock97559372014-10-24 16:27:36 -04001828 /** @see AudioManager#isValidRingerMode(int) */
1829 public boolean isValidRingerMode(int ringerMode) {
1830 return ringerMode >= 0 && ringerMode <= AudioManager.RINGER_MODE_MAX;
1831 }
1832
John Spurlock661f2cf2014-11-17 10:29:10 -05001833 public void setRingerModeExternal(int ringerMode, String caller) {
John Spurlockaf88a192014-12-23 16:14:44 -05001834 setRingerMode(ringerMode, caller, true /*external*/);
John Spurlock661f2cf2014-11-17 10:29:10 -05001835 }
1836
1837 public void setRingerModeInternal(int ringerMode, String caller) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05001838 enforceVolumeController("setRingerModeInternal");
John Spurlockaf88a192014-12-23 16:14:44 -05001839 setRingerMode(ringerMode, caller, false /*external*/);
John Spurlock661f2cf2014-11-17 10:29:10 -05001840 }
1841
1842 private void setRingerMode(int ringerMode, String caller, boolean external) {
Eric Laurent212532b2014-07-21 15:43:18 -07001843 if (mUseFixedVolume || isPlatformTelevision()) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001844 return;
1845 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001846 if (caller == null || caller.length() == 0) {
1847 throw new IllegalArgumentException("Bad caller: " + caller);
1848 }
John Spurlock97559372014-10-24 16:27:36 -04001849 ensureValidRingerMode(ringerMode);
Eric Laurent24482012012-05-10 09:41:17 -07001850 if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) {
1851 ringerMode = AudioManager.RINGER_MODE_SILENT;
1852 }
John Spurlockaf88a192014-12-23 16:14:44 -05001853 final long identity = Binder.clearCallingIdentity();
1854 try {
1855 synchronized (mSettingsLock) {
1856 final int ringerModeInternal = getRingerModeInternal();
1857 final int ringerModeExternal = getRingerModeExternal();
1858 if (external) {
1859 setRingerModeExt(ringerMode);
1860 if (mRingerModeDelegate != null) {
1861 ringerMode = mRingerModeDelegate.onSetRingerModeExternal(ringerModeExternal,
1862 ringerMode, caller, ringerModeInternal);
1863 }
1864 if (ringerMode != ringerModeInternal) {
1865 setRingerModeInt(ringerMode, true /*persist*/);
1866 }
1867 } else /*internal*/ {
1868 if (ringerMode != ringerModeInternal) {
1869 setRingerModeInt(ringerMode, true /*persist*/);
1870 }
1871 if (mRingerModeDelegate != null) {
1872 ringerMode = mRingerModeDelegate.onSetRingerModeInternal(ringerModeInternal,
1873 ringerMode, caller, ringerModeExternal);
1874 }
1875 setRingerModeExt(ringerMode);
John Spurlock57627792014-12-11 11:29:54 -05001876 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001877 }
John Spurlockaf88a192014-12-23 16:14:44 -05001878 } finally {
1879 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
1881 }
1882
John Spurlock661f2cf2014-11-17 10:29:10 -05001883 private void setRingerModeExt(int ringerMode) {
1884 synchronized(mSettingsLock) {
1885 if (ringerMode == mRingerModeExternal) return;
1886 mRingerModeExternal = ringerMode;
John Spurlocke5b42d92014-10-15 12:03:48 -04001887 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001888 // Send sticky broadcast
John Spurlockbcc10872014-11-28 15:29:21 -05001889 broadcastRingerMode(AudioManager.RINGER_MODE_CHANGED_ACTION, ringerMode);
John Spurlocke5b42d92014-10-15 12:03:48 -04001890 }
1891
Eric Laurent4050c932009-07-08 02:52:14 -07001892 private void setRingerModeInt(int ringerMode, boolean persist) {
John Spurlockbcc10872014-11-28 15:29:21 -05001893 final boolean change;
Glenn Kastenba195eb2011-12-13 09:30:40 -08001894 synchronized(mSettingsLock) {
John Spurlockbcc10872014-11-28 15:29:21 -05001895 change = mRingerMode != ringerMode;
Glenn Kastenba195eb2011-12-13 09:30:40 -08001896 mRingerMode = ringerMode;
1897 }
Jason Parekhb1096152009-03-24 17:48:25 -07001898
Eric Laurent5b4e6542010-03-19 20:02:21 -07001899 // Mute stream if not previously muted by ringer mode and ringer mode
1900 // is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
1901 // Unmute stream if previously muted by ringer mode and ringer mode
1902 // is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
Jason Parekhb1096152009-03-24 17:48:25 -07001903 int numStreamTypes = AudioSystem.getNumStreamTypes();
John Spurlock661f2cf2014-11-17 10:29:10 -05001904 final boolean ringerModeMute = ringerMode == AudioManager.RINGER_MODE_VIBRATE
1905 || ringerMode == AudioManager.RINGER_MODE_SILENT;
Eric Laurent5b4e6542010-03-19 20:02:21 -07001906 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
John Spurlock661f2cf2014-11-17 10:29:10 -05001907 final boolean isMuted = isStreamMutedByRingerMode(streamType);
1908 final boolean shouldMute = ringerModeMute && isStreamAffectedByRingerMode(streamType);
1909 if (isMuted == shouldMute) continue;
1910 if (!shouldMute) {
1911 // unmute
1912 // ring and notifications volume should never be 0 when not silenced
1913 // on voice capable devices or devices that support vibration
1914 if ((isPlatformVoice() || mHasVibrator) &&
1915 mStreamVolumeAlias[streamType] == AudioSystem.STREAM_RING) {
1916 synchronized (VolumeStreamState.class) {
1917 Set set = mStreamStates[streamType].mIndex.entrySet();
1918 Iterator i = set.iterator();
1919 while (i.hasNext()) {
1920 Map.Entry entry = (Map.Entry)i.next();
1921 if ((Integer)entry.getValue() == 0) {
1922 entry.setValue(10);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001923 }
1924 }
Eric Laurentb024c302011-10-14 17:19:27 -07001925 }
Eric Laurent9bcf4012009-06-12 06:09:28 -07001926 }
RoboErik4197cb62015-01-21 15:45:32 -08001927 mStreamStates[streamType].mute(false);
John Spurlock661f2cf2014-11-17 10:29:10 -05001928 mRingerModeMutedStreams &= ~(1 << streamType);
Eric Laurent5b4e6542010-03-19 20:02:21 -07001929 } else {
John Spurlock661f2cf2014-11-17 10:29:10 -05001930 // mute
RoboErik4197cb62015-01-21 15:45:32 -08001931 mStreamStates[streamType].mute(true);
John Spurlock661f2cf2014-11-17 10:29:10 -05001932 mRingerModeMutedStreams |= (1 << streamType);
Jason Parekhb1096152009-03-24 17:48:25 -07001933 }
1934 }
Eric Laurenta553c252009-07-17 12:17:14 -07001935
Jason Parekhb1096152009-03-24 17:48:25 -07001936 // Post a persist ringer mode msg
Eric Laurent4050c932009-07-08 02:52:14 -07001937 if (persist) {
Eric Laurentafbb0472011-12-15 09:04:23 -08001938 sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE,
Eric Laurent4050c932009-07-08 02:52:14 -07001939 SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
1940 }
John Spurlockbcc10872014-11-28 15:29:21 -05001941 if (change) {
1942 // Send sticky broadcast
1943 broadcastRingerMode(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION, ringerMode);
1944 }
Jason Parekhb1096152009-03-24 17:48:25 -07001945 }
1946
Mike Lockwood90631542012-01-06 11:20:37 -05001947 private void restoreMasterVolume() {
Eric Laurent83a017b2013-03-19 18:15:31 -07001948 if (mUseFixedVolume) {
1949 AudioSystem.setMasterVolume(1.0f);
1950 return;
1951 }
Mike Lockwood90631542012-01-06 11:20:37 -05001952 if (mUseMasterVolume) {
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07001953 float volume = Settings.System.getFloatForUser(mContentResolver,
1954 Settings.System.VOLUME_MASTER, -1.0f, UserHandle.USER_CURRENT);
Mike Lockwood90631542012-01-06 11:20:37 -05001955 if (volume >= 0.0f) {
1956 AudioSystem.setMasterVolume(volume);
1957 }
1958 }
1959 }
1960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 /** @see AudioManager#shouldVibrate(int) */
1962 public boolean shouldVibrate(int vibrateType) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07001963 if (!mHasVibrator) return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964
1965 switch (getVibrateSetting(vibrateType)) {
1966
1967 case AudioManager.VIBRATE_SETTING_ON:
John Spurlock57627792014-12-11 11:29:54 -05001968 return getRingerModeExternal() != AudioManager.RINGER_MODE_SILENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969
1970 case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
John Spurlock57627792014-12-11 11:29:54 -05001971 return getRingerModeExternal() == AudioManager.RINGER_MODE_VIBRATE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972
1973 case AudioManager.VIBRATE_SETTING_OFF:
Daniel Sandlerbcac4962010-04-12 13:23:57 -04001974 // return false, even for incoming calls
1975 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976
1977 default:
1978 return false;
1979 }
1980 }
1981
1982 /** @see AudioManager#getVibrateSetting(int) */
1983 public int getVibrateSetting(int vibrateType) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07001984 if (!mHasVibrator) return AudioManager.VIBRATE_SETTING_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 return (mVibrateSetting >> (vibrateType * 2)) & 3;
1986 }
1987
1988 /** @see AudioManager#setVibrateSetting(int, int) */
1989 public void setVibrateSetting(int vibrateType, int vibrateSetting) {
1990
Eric Laurentbffc3d12012-05-07 17:43:49 -07001991 if (!mHasVibrator) return;
1992
John Spurlock61560172015-02-06 19:46:04 -05001993 mVibrateSetting = AudioSystem.getValueForVibrateSetting(mVibrateSetting, vibrateType,
1994 vibrateSetting);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995
1996 // Broadcast change
1997 broadcastVibrateSetting(vibrateType);
1998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
2000
Eric Laurent9272b4b2010-01-23 17:12:59 -08002001 private class SetModeDeathHandler implements IBinder.DeathRecipient {
2002 private IBinder mCb; // To be notified of client's death
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002003 private int mPid;
Eric Laurent9272b4b2010-01-23 17:12:59 -08002004 private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
2005
Eric Laurent9f103de2011-09-08 15:04:23 -07002006 SetModeDeathHandler(IBinder cb, int pid) {
Eric Laurent9272b4b2010-01-23 17:12:59 -08002007 mCb = cb;
Eric Laurent9f103de2011-09-08 15:04:23 -07002008 mPid = pid;
Eric Laurent9272b4b2010-01-23 17:12:59 -08002009 }
2010
2011 public void binderDied() {
Eric Laurentd7454be2011-09-14 08:45:58 -07002012 int newModeOwnerPid = 0;
Eric Laurent9272b4b2010-01-23 17:12:59 -08002013 synchronized(mSetModeDeathHandlers) {
2014 Log.w(TAG, "setMode() client died");
2015 int index = mSetModeDeathHandlers.indexOf(this);
2016 if (index < 0) {
2017 Log.w(TAG, "unregistered setMode() client died");
2018 } else {
Eric Laurentd7454be2011-09-14 08:45:58 -07002019 newModeOwnerPid = setModeInt(AudioSystem.MODE_NORMAL, mCb, mPid);
Eric Laurent9272b4b2010-01-23 17:12:59 -08002020 }
2021 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002022 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
2023 // SCO connections not started by the application changing the mode
Eric Laurentd7454be2011-09-14 08:45:58 -07002024 if (newModeOwnerPid != 0) {
Eric Laurent6b5e22d2013-03-28 16:10:45 -07002025 final long ident = Binder.clearCallingIdentity();
2026 disconnectBluetoothSco(newModeOwnerPid);
2027 Binder.restoreCallingIdentity(ident);
Eric Laurent9f103de2011-09-08 15:04:23 -07002028 }
Eric Laurent9272b4b2010-01-23 17:12:59 -08002029 }
2030
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002031 public int getPid() {
2032 return mPid;
2033 }
2034
Eric Laurent9272b4b2010-01-23 17:12:59 -08002035 public void setMode(int mode) {
2036 mMode = mode;
2037 }
2038
2039 public int getMode() {
2040 return mMode;
2041 }
2042
2043 public IBinder getBinder() {
2044 return mCb;
2045 }
2046 }
2047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 /** @see AudioManager#setMode(int) */
Eric Laurent9272b4b2010-01-23 17:12:59 -08002049 public void setMode(int mode, IBinder cb) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002050 if (DEBUG_MODE) { Log.v(TAG, "setMode(mode=" + mode + ")"); }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 if (!checkAudioSettingsPermission("setMode()")) {
2052 return;
2053 }
Eric Laurenta553c252009-07-17 12:17:14 -07002054
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07002055 if ( (mode == AudioSystem.MODE_IN_CALL) &&
2056 (mContext.checkCallingOrSelfPermission(
2057 android.Manifest.permission.MODIFY_PHONE_STATE)
2058 != PackageManager.PERMISSION_GRANTED)) {
2059 Log.w(TAG, "MODIFY_PHONE_STATE Permission Denial: setMode(MODE_IN_CALL) from pid="
2060 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
2061 return;
2062 }
2063
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08002064 if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) {
Eric Laurenta553c252009-07-17 12:17:14 -07002065 return;
2066 }
2067
Eric Laurentd7454be2011-09-14 08:45:58 -07002068 int newModeOwnerPid = 0;
Eric Laurent9f103de2011-09-08 15:04:23 -07002069 synchronized(mSetModeDeathHandlers) {
Eric Laurenta553c252009-07-17 12:17:14 -07002070 if (mode == AudioSystem.MODE_CURRENT) {
2071 mode = mMode;
2072 }
Eric Laurentd7454be2011-09-14 08:45:58 -07002073 newModeOwnerPid = setModeInt(mode, cb, Binder.getCallingPid());
Eric Laurent9f103de2011-09-08 15:04:23 -07002074 }
2075 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
2076 // SCO connections not started by the application changing the mode
Eric Laurentd7454be2011-09-14 08:45:58 -07002077 if (newModeOwnerPid != 0) {
2078 disconnectBluetoothSco(newModeOwnerPid);
Eric Laurent9f103de2011-09-08 15:04:23 -07002079 }
2080 }
Jean-Michel Trivi2ade5762010-12-11 13:18:30 -08002081
Eric Laurent9f103de2011-09-08 15:04:23 -07002082 // must be called synchronized on mSetModeDeathHandlers
Eric Laurentd7454be2011-09-14 08:45:58 -07002083 // setModeInt() returns a valid PID if the audio mode was successfully set to
Eric Laurent9f103de2011-09-08 15:04:23 -07002084 // any mode other than NORMAL.
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07002085 private int setModeInt(int mode, IBinder cb, int pid) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002086 if (DEBUG_MODE) { Log.v(TAG, "setModeInt(mode=" + mode + ", pid=" + pid + ")"); }
Eric Laurentd7454be2011-09-14 08:45:58 -07002087 int newModeOwnerPid = 0;
Eric Laurent9f103de2011-09-08 15:04:23 -07002088 if (cb == null) {
2089 Log.e(TAG, "setModeInt() called with null binder");
Eric Laurentd7454be2011-09-14 08:45:58 -07002090 return newModeOwnerPid;
Eric Laurent9f103de2011-09-08 15:04:23 -07002091 }
Jean-Michel Trivi2ade5762010-12-11 13:18:30 -08002092
Eric Laurent9f103de2011-09-08 15:04:23 -07002093 SetModeDeathHandler hdlr = null;
2094 Iterator iter = mSetModeDeathHandlers.iterator();
2095 while (iter.hasNext()) {
2096 SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
2097 if (h.getPid() == pid) {
2098 hdlr = h;
2099 // Remove from client list so that it is re-inserted at top of list
2100 iter.remove();
2101 hdlr.getBinder().unlinkToDeath(hdlr, 0);
2102 break;
2103 }
2104 }
2105 int status = AudioSystem.AUDIO_STATUS_OK;
2106 do {
2107 if (mode == AudioSystem.MODE_NORMAL) {
2108 // get new mode from client at top the list if any
2109 if (!mSetModeDeathHandlers.isEmpty()) {
2110 hdlr = mSetModeDeathHandlers.get(0);
2111 cb = hdlr.getBinder();
2112 mode = hdlr.getMode();
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002113 if (DEBUG_MODE) {
2114 Log.w(TAG, " using mode=" + mode + " instead due to death hdlr at pid="
2115 + hdlr.mPid);
2116 }
Eric Laurentb9c9d262009-05-06 08:13:20 -07002117 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002118 } else {
2119 if (hdlr == null) {
2120 hdlr = new SetModeDeathHandler(cb, pid);
2121 }
2122 // Register for client death notification
2123 try {
2124 cb.linkToDeath(hdlr, 0);
2125 } catch (RemoteException e) {
2126 // Client has died!
2127 Log.w(TAG, "setMode() could not link to "+cb+" binder death");
2128 }
2129
2130 // Last client to call setMode() is always at top of client list
2131 // as required by SetModeDeathHandler.binderDied()
2132 mSetModeDeathHandlers.add(0, hdlr);
2133 hdlr.setMode(mode);
2134 }
2135
2136 if (mode != mMode) {
2137 status = AudioSystem.setPhoneState(mode);
2138 if (status == AudioSystem.AUDIO_STATUS_OK) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002139 if (DEBUG_MODE) { Log.v(TAG, " mode successfully set to " + mode); }
Eric Laurent9f103de2011-09-08 15:04:23 -07002140 mMode = mode;
2141 } else {
2142 if (hdlr != null) {
2143 mSetModeDeathHandlers.remove(hdlr);
2144 cb.unlinkToDeath(hdlr, 0);
2145 }
2146 // force reading new top of mSetModeDeathHandlers stack
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002147 if (DEBUG_MODE) { Log.w(TAG, " mode set to MODE_NORMAL after phoneState pb"); }
Eric Laurent9f103de2011-09-08 15:04:23 -07002148 mode = AudioSystem.MODE_NORMAL;
2149 }
2150 } else {
2151 status = AudioSystem.AUDIO_STATUS_OK;
2152 }
2153 } while (status != AudioSystem.AUDIO_STATUS_OK && !mSetModeDeathHandlers.isEmpty());
2154
2155 if (status == AudioSystem.AUDIO_STATUS_OK) {
2156 if (mode != AudioSystem.MODE_NORMAL) {
Eric Laurentd7454be2011-09-14 08:45:58 -07002157 if (mSetModeDeathHandlers.isEmpty()) {
2158 Log.e(TAG, "setMode() different from MODE_NORMAL with empty mode client stack");
2159 } else {
2160 newModeOwnerPid = mSetModeDeathHandlers.get(0).getPid();
2161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163 int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08002164 int device = getDeviceForStream(streamType);
Eric Laurent42b041e2013-03-29 11:36:03 -07002165 int index = mStreamStates[mStreamVolumeAlias[streamType]].getIndex(device);
2166 setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, true);
Eric Laurent6d517662012-04-23 18:42:39 -07002167
2168 updateStreamVolumeAlias(true /*updateVolumes*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
Eric Laurentd7454be2011-09-14 08:45:58 -07002170 return newModeOwnerPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
2172
2173 /** @see AudioManager#getMode() */
2174 public int getMode() {
2175 return mMode;
2176 }
2177
Eric Laurente78fced2013-03-15 16:03:47 -07002178 //==========================================================================================
2179 // Sound Effects
2180 //==========================================================================================
2181
2182 private static final String TAG_AUDIO_ASSETS = "audio_assets";
2183 private static final String ATTR_VERSION = "version";
2184 private static final String TAG_GROUP = "group";
2185 private static final String ATTR_GROUP_NAME = "name";
2186 private static final String TAG_ASSET = "asset";
2187 private static final String ATTR_ASSET_ID = "id";
2188 private static final String ATTR_ASSET_FILE = "file";
2189
2190 private static final String ASSET_FILE_VERSION = "1.0";
2191 private static final String GROUP_TOUCH_SOUNDS = "touch_sounds";
2192
Glenn Kasten167d1a22013-07-23 16:24:41 -07002193 private static final int SOUND_EFFECTS_LOAD_TIMEOUT_MS = 5000;
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002194
2195 class LoadSoundEffectReply {
2196 public int mStatus = 1;
2197 };
2198
Eric Laurente78fced2013-03-15 16:03:47 -07002199 private void loadTouchSoundAssetDefaults() {
2200 SOUND_EFFECT_FILES.add("Effect_Tick.ogg");
2201 for (int i = 0; i < AudioManager.NUM_SOUND_EFFECTS; i++) {
2202 SOUND_EFFECT_FILES_MAP[i][0] = 0;
2203 SOUND_EFFECT_FILES_MAP[i][1] = -1;
2204 }
2205 }
2206
2207 private void loadTouchSoundAssets() {
2208 XmlResourceParser parser = null;
2209
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002210 // only load assets once.
2211 if (!SOUND_EFFECT_FILES.isEmpty()) {
2212 return;
2213 }
2214
Eric Laurente78fced2013-03-15 16:03:47 -07002215 loadTouchSoundAssetDefaults();
2216
2217 try {
2218 parser = mContext.getResources().getXml(com.android.internal.R.xml.audio_assets);
2219
2220 XmlUtils.beginDocument(parser, TAG_AUDIO_ASSETS);
2221 String version = parser.getAttributeValue(null, ATTR_VERSION);
2222 boolean inTouchSoundsGroup = false;
2223
2224 if (ASSET_FILE_VERSION.equals(version)) {
2225 while (true) {
2226 XmlUtils.nextElement(parser);
2227 String element = parser.getName();
2228 if (element == null) {
2229 break;
2230 }
2231 if (element.equals(TAG_GROUP)) {
2232 String name = parser.getAttributeValue(null, ATTR_GROUP_NAME);
2233 if (GROUP_TOUCH_SOUNDS.equals(name)) {
2234 inTouchSoundsGroup = true;
2235 break;
2236 }
2237 }
2238 }
2239 while (inTouchSoundsGroup) {
2240 XmlUtils.nextElement(parser);
2241 String element = parser.getName();
2242 if (element == null) {
2243 break;
2244 }
2245 if (element.equals(TAG_ASSET)) {
2246 String id = parser.getAttributeValue(null, ATTR_ASSET_ID);
2247 String file = parser.getAttributeValue(null, ATTR_ASSET_FILE);
2248 int fx;
2249
2250 try {
2251 Field field = AudioManager.class.getField(id);
2252 fx = field.getInt(null);
2253 } catch (Exception e) {
2254 Log.w(TAG, "Invalid touch sound ID: "+id);
2255 continue;
2256 }
2257
2258 int i = SOUND_EFFECT_FILES.indexOf(file);
2259 if (i == -1) {
2260 i = SOUND_EFFECT_FILES.size();
2261 SOUND_EFFECT_FILES.add(file);
2262 }
2263 SOUND_EFFECT_FILES_MAP[fx][0] = i;
2264 } else {
2265 break;
2266 }
2267 }
2268 }
2269 } catch (Resources.NotFoundException e) {
2270 Log.w(TAG, "audio assets file not found", e);
2271 } catch (XmlPullParserException e) {
2272 Log.w(TAG, "XML parser exception reading touch sound assets", e);
2273 } catch (IOException e) {
2274 Log.w(TAG, "I/O exception reading touch sound assets", e);
2275 } finally {
2276 if (parser != null) {
2277 parser.close();
2278 }
2279 }
2280 }
2281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 /** @see AudioManager#playSoundEffect(int) */
2283 public void playSoundEffect(int effectType) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002284 playSoundEffectVolume(effectType, -1.0f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
2286
2287 /** @see AudioManager#playSoundEffect(int, float) */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 public void playSoundEffectVolume(int effectType, float volume) {
Natalie Silvanovich559c76d2014-05-01 10:16:24 -07002289 if (effectType >= AudioManager.NUM_SOUND_EFFECTS || effectType < 0) {
2290 Log.w(TAG, "AudioService effectType value " + effectType + " out of range");
2291 return;
2292 }
2293
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002294 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_QUEUE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 effectType, (int) (volume * 1000), null, 0);
2296 }
2297
2298 /**
2299 * Loads samples into the soundpool.
Glenn Kasten5c17a822011-11-30 09:41:01 -08002300 * This method must be called at first when sound effects are enabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 */
2302 public boolean loadSoundEffects() {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002303 int attempts = 3;
2304 LoadSoundEffectReply reply = new LoadSoundEffectReply();
Eric Laurenta60e2122010-12-28 16:49:07 -08002305
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002306 synchronized (reply) {
2307 sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, reply, 0);
2308 while ((reply.mStatus == 1) && (attempts-- > 0)) {
Eric Laurent117b7bb2011-01-16 17:07:27 -08002309 try {
Glenn Kasten167d1a22013-07-23 16:24:41 -07002310 reply.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002311 } catch (InterruptedException e) {
2312 Log.w(TAG, "loadSoundEffects Interrupted while waiting sound pool loaded.");
Eric Laurent117b7bb2011-01-16 17:07:27 -08002313 }
Eric Laurenta60e2122010-12-28 16:49:07 -08002314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002316 return (reply.mStatus == 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 }
2318
2319 /**
2320 * Unloads samples from the sound pool.
2321 * This method can be called to free some memory when
2322 * sound effects are disabled.
2323 */
2324 public void unloadSoundEffects() {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002325 sendMsg(mAudioHandler, MSG_UNLOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 }
2327
Eric Laurenta60e2122010-12-28 16:49:07 -08002328 class SoundPoolListenerThread extends Thread {
2329 public SoundPoolListenerThread() {
2330 super("SoundPoolListenerThread");
2331 }
2332
2333 @Override
2334 public void run() {
2335
2336 Looper.prepare();
2337 mSoundPoolLooper = Looper.myLooper();
2338
2339 synchronized (mSoundEffectsLock) {
2340 if (mSoundPool != null) {
2341 mSoundPoolCallBack = new SoundPoolCallback();
2342 mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack);
2343 }
2344 mSoundEffectsLock.notify();
2345 }
2346 Looper.loop();
2347 }
2348 }
2349
2350 private final class SoundPoolCallback implements
2351 android.media.SoundPool.OnLoadCompleteListener {
2352
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002353 int mStatus = 1; // 1 means neither error nor last sample loaded yet
2354 List<Integer> mSamples = new ArrayList<Integer>();
Eric Laurenta60e2122010-12-28 16:49:07 -08002355
2356 public int status() {
2357 return mStatus;
2358 }
2359
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002360 public void setSamples(int[] samples) {
2361 for (int i = 0; i < samples.length; i++) {
2362 // do not wait ack for samples rejected upfront by SoundPool
2363 if (samples[i] > 0) {
2364 mSamples.add(samples[i]);
2365 }
2366 }
Eric Laurenta60e2122010-12-28 16:49:07 -08002367 }
2368
2369 public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
2370 synchronized (mSoundEffectsLock) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002371 int i = mSamples.indexOf(sampleId);
2372 if (i >= 0) {
2373 mSamples.remove(i);
Eric Laurenta60e2122010-12-28 16:49:07 -08002374 }
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002375 if ((status != 0) || mSamples. isEmpty()) {
2376 mStatus = status;
Eric Laurenta60e2122010-12-28 16:49:07 -08002377 mSoundEffectsLock.notify();
2378 }
2379 }
2380 }
2381 }
2382
Eric Laurent4050c932009-07-08 02:52:14 -07002383 /** @see AudioManager#reloadAudioSettings() */
2384 public void reloadAudioSettings() {
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07002385 readAudioSettings(false /*userSwitch*/);
2386 }
2387
2388 private void readAudioSettings(boolean userSwitch) {
Eric Laurent4050c932009-07-08 02:52:14 -07002389 // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
2390 readPersistedSettings();
2391
2392 // restore volume settings
2393 int numStreamTypes = AudioSystem.getNumStreamTypes();
2394 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
2395 VolumeStreamState streamState = mStreamStates[streamType];
2396
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07002397 if (userSwitch && mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) {
2398 continue;
2399 }
2400
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07002401 streamState.readSettings();
2402 synchronized (VolumeStreamState.class) {
Eric Laurent3172d5e2012-05-09 11:38:16 -07002403 // unmute stream that was muted but is not affect by mute anymore
RoboErik4197cb62015-01-21 15:45:32 -08002404 if (streamState.mIsMuted && ((!isStreamAffectedByMute(streamType) &&
Eric Laurent83a017b2013-03-19 18:15:31 -07002405 !isStreamMutedByRingerMode(streamType)) || mUseFixedVolume)) {
RoboErik4197cb62015-01-21 15:45:32 -08002406 streamState.mIsMuted = false;
Eric Laurent4050c932009-07-08 02:52:14 -07002407 }
Eric Laurent4050c932009-07-08 02:52:14 -07002408 }
2409 }
2410
Eric Laurent33902db2012-10-07 16:15:07 -07002411 // apply new ringer mode before checking volume for alias streams so that streams
2412 // muted by ringer mode have the correct volume
John Spurlock661f2cf2014-11-17 10:29:10 -05002413 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent33902db2012-10-07 16:15:07 -07002414
Eric Laurent212532b2014-07-21 15:43:18 -07002415 checkAllFixedVolumeDevices();
Eric Laurent24482012012-05-10 09:41:17 -07002416 checkAllAliasStreamVolumes();
2417
Eric Laurentd640bd32012-09-28 18:01:48 -07002418 synchronized (mSafeMediaVolumeState) {
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002419 mMusicActiveMs = MathUtils.constrain(Settings.Secure.getIntForUser(mContentResolver,
2420 Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, 0, UserHandle.USER_CURRENT),
2421 0, UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX);
Eric Laurentd640bd32012-09-28 18:01:48 -07002422 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) {
Eric Laurentf1a457d2012-09-20 16:27:23 -07002423 enforceSafeMediaVolume();
2424 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07002425 }
Eric Laurent4050c932009-07-08 02:52:14 -07002426 }
2427
Dianne Hackborn961cae92013-03-20 14:59:43 -07002428 /** @see AudioManager#setSpeakerphoneOn(boolean) */
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002429 public void setSpeakerphoneOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -07002430 if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
2431 return;
2432 }
Johan Gustavsson7337bee2013-03-01 15:53:30 +01002433
2434 if (on) {
2435 if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
2436 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
2437 AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE, null, 0);
2438 }
2439 mForcedUseForComm = AudioSystem.FORCE_SPEAKER;
2440 } else if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER){
2441 mForcedUseForComm = AudioSystem.FORCE_NONE;
2442 }
Eric Laurentfa640152011-03-12 15:59:51 -08002443
Eric Laurentafbb0472011-12-15 09:04:23 -08002444 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002445 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002446 }
2447
2448 /** @see AudioManager#isSpeakerphoneOn() */
2449 public boolean isSpeakerphoneOn() {
Eric Laurentfa640152011-03-12 15:59:51 -08002450 return (mForcedUseForComm == AudioSystem.FORCE_SPEAKER);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002451 }
2452
Dianne Hackborn961cae92013-03-20 14:59:43 -07002453 /** @see AudioManager#setBluetoothScoOn(boolean) */
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002454 public void setBluetoothScoOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -07002455 if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
2456 return;
2457 }
Johan Gustavsson7337bee2013-03-01 15:53:30 +01002458
2459 if (on) {
2460 mForcedUseForComm = AudioSystem.FORCE_BT_SCO;
2461 } else if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
2462 mForcedUseForComm = AudioSystem.FORCE_NONE;
2463 }
Eric Laurentfa640152011-03-12 15:59:51 -08002464
Eric Laurentafbb0472011-12-15 09:04:23 -08002465 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002466 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
Eric Laurentafbb0472011-12-15 09:04:23 -08002467 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002468 AudioSystem.FOR_RECORD, mForcedUseForComm, null, 0);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002469 }
2470
2471 /** @see AudioManager#isBluetoothScoOn() */
2472 public boolean isBluetoothScoOn() {
Eric Laurentfa640152011-03-12 15:59:51 -08002473 return (mForcedUseForComm == AudioSystem.FORCE_BT_SCO);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002474 }
2475
Dianne Hackborn961cae92013-03-20 14:59:43 -07002476 /** @see AudioManager#setBluetoothA2dpOn(boolean) */
Eric Laurent78472112012-05-21 08:57:21 -07002477 public void setBluetoothA2dpOn(boolean on) {
Eric Laurentc390bed2012-07-03 12:24:05 -07002478 synchronized (mBluetoothA2dpEnabledLock) {
2479 mBluetoothA2dpEnabled = on;
2480 sendMsg(mAudioHandler, MSG_SET_FORCE_BT_A2DP_USE, SENDMSG_QUEUE,
2481 AudioSystem.FOR_MEDIA,
2482 mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP,
2483 null, 0);
2484 }
Eric Laurent78472112012-05-21 08:57:21 -07002485 }
2486
2487 /** @see AudioManager#isBluetoothA2dpOn() */
2488 public boolean isBluetoothA2dpOn() {
2489 synchronized (mBluetoothA2dpEnabledLock) {
2490 return mBluetoothA2dpEnabled;
2491 }
2492 }
2493
Eric Laurent3def1ee2010-03-17 23:26:26 -07002494 /** @see AudioManager#startBluetoothSco() */
Eric Laurent83900752014-05-15 15:14:22 -07002495 public void startBluetoothSco(IBinder cb, int targetSdkVersion) {
2496 int scoAudioMode =
2497 (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR2) ?
Liejun Taof4e51d82014-07-16 11:18:29 -07002498 SCO_MODE_VIRTUAL_CALL : SCO_MODE_UNDEFINED;
Eric Laurent83900752014-05-15 15:14:22 -07002499 startBluetoothScoInt(cb, scoAudioMode);
2500 }
2501
2502 /** @see AudioManager#startBluetoothScoVirtualCall() */
2503 public void startBluetoothScoVirtualCall(IBinder cb) {
2504 startBluetoothScoInt(cb, SCO_MODE_VIRTUAL_CALL);
2505 }
2506
2507 void startBluetoothScoInt(IBinder cb, int scoAudioMode){
Eric Laurentdc03c612011-04-01 10:59:41 -07002508 if (!checkAudioSettingsPermission("startBluetoothSco()") ||
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002509 !mSystemReady) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002510 return;
2511 }
Eric Laurent854938a2011-02-22 12:05:20 -08002512 ScoClient client = getScoClient(cb, true);
Eric Laurentf5a1fc32013-03-11 18:52:57 -07002513 // The calling identity must be cleared before calling ScoClient.incCount().
2514 // inCount() calls requestScoState() which in turn can call BluetoothHeadset APIs
2515 // and this must be done on behalf of system server to make sure permissions are granted.
2516 // The caller identity must be cleared after getScoClient() because it is needed if a new
2517 // client is created.
2518 final long ident = Binder.clearCallingIdentity();
Eric Laurent83900752014-05-15 15:14:22 -07002519 client.incCount(scoAudioMode);
Eric Laurent2a57ca92013-03-07 17:29:27 -08002520 Binder.restoreCallingIdentity(ident);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002521 }
2522
2523 /** @see AudioManager#stopBluetoothSco() */
2524 public void stopBluetoothSco(IBinder cb){
Eric Laurentdc03c612011-04-01 10:59:41 -07002525 if (!checkAudioSettingsPermission("stopBluetoothSco()") ||
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002526 !mSystemReady) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002527 return;
2528 }
Eric Laurent854938a2011-02-22 12:05:20 -08002529 ScoClient client = getScoClient(cb, false);
Eric Laurentf5a1fc32013-03-11 18:52:57 -07002530 // The calling identity must be cleared before calling ScoClient.decCount().
2531 // decCount() calls requestScoState() which in turn can call BluetoothHeadset APIs
2532 // and this must be done on behalf of system server to make sure permissions are granted.
2533 final long ident = Binder.clearCallingIdentity();
Eric Laurent854938a2011-02-22 12:05:20 -08002534 if (client != null) {
2535 client.decCount();
2536 }
Eric Laurent2a57ca92013-03-07 17:29:27 -08002537 Binder.restoreCallingIdentity(ident);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002538 }
2539
Eric Laurent78472112012-05-21 08:57:21 -07002540
Eric Laurent3def1ee2010-03-17 23:26:26 -07002541 private class ScoClient implements IBinder.DeathRecipient {
2542 private IBinder mCb; // To be notified of client's death
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002543 private int mCreatorPid;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002544 private int mStartcount; // number of SCO connections started by this client
2545
2546 ScoClient(IBinder cb) {
2547 mCb = cb;
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002548 mCreatorPid = Binder.getCallingPid();
Eric Laurent3def1ee2010-03-17 23:26:26 -07002549 mStartcount = 0;
2550 }
2551
2552 public void binderDied() {
2553 synchronized(mScoClients) {
2554 Log.w(TAG, "SCO client died");
2555 int index = mScoClients.indexOf(this);
2556 if (index < 0) {
2557 Log.w(TAG, "unregistered SCO client died");
2558 } else {
2559 clearCount(true);
2560 mScoClients.remove(this);
2561 }
2562 }
2563 }
2564
Eric Laurent83900752014-05-15 15:14:22 -07002565 public void incCount(int scoAudioMode) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002566 synchronized(mScoClients) {
Eric Laurent83900752014-05-15 15:14:22 -07002567 requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED, scoAudioMode);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002568 if (mStartcount == 0) {
2569 try {
2570 mCb.linkToDeath(this, 0);
2571 } catch (RemoteException e) {
2572 // client has already died!
2573 Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death");
2574 }
2575 }
2576 mStartcount++;
2577 }
2578 }
2579
2580 public void decCount() {
2581 synchronized(mScoClients) {
2582 if (mStartcount == 0) {
2583 Log.w(TAG, "ScoClient.decCount() already 0");
2584 } else {
2585 mStartcount--;
2586 if (mStartcount == 0) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07002587 try {
2588 mCb.unlinkToDeath(this, 0);
2589 } catch (NoSuchElementException e) {
2590 Log.w(TAG, "decCount() going to 0 but not registered to binder");
2591 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002592 }
Eric Laurentc18c9132013-04-12 17:24:56 -07002593 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, 0);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002594 }
2595 }
2596 }
2597
2598 public void clearCount(boolean stopSco) {
2599 synchronized(mScoClients) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07002600 if (mStartcount != 0) {
2601 try {
2602 mCb.unlinkToDeath(this, 0);
2603 } catch (NoSuchElementException e) {
2604 Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
2605 }
2606 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002607 mStartcount = 0;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002608 if (stopSco) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002609 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, 0);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002610 }
2611 }
2612 }
2613
2614 public int getCount() {
2615 return mStartcount;
2616 }
2617
2618 public IBinder getBinder() {
2619 return mCb;
2620 }
2621
Eric Laurentd7454be2011-09-14 08:45:58 -07002622 public int getPid() {
2623 return mCreatorPid;
2624 }
2625
Eric Laurent3def1ee2010-03-17 23:26:26 -07002626 public int totalCount() {
2627 synchronized(mScoClients) {
2628 int count = 0;
2629 int size = mScoClients.size();
2630 for (int i = 0; i < size; i++) {
2631 count += mScoClients.get(i).getCount();
2632 }
2633 return count;
2634 }
2635 }
2636
Eric Laurent83900752014-05-15 15:14:22 -07002637 private void requestScoState(int state, int scoAudioMode) {
Eric Laurent62ef7672010-11-24 10:58:32 -08002638 checkScoAudioState();
Eric Laurentdc03c612011-04-01 10:59:41 -07002639 if (totalCount() == 0) {
2640 if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
2641 // Make sure that the state transitions to CONNECTING even if we cannot initiate
2642 // the connection.
2643 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
2644 // Accept SCO audio activation only in NORMAL audio mode or if the mode is
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002645 // currently controlled by the same client process.
Eric Laurent9f103de2011-09-08 15:04:23 -07002646 synchronized(mSetModeDeathHandlers) {
2647 if ((mSetModeDeathHandlers.isEmpty() ||
2648 mSetModeDeathHandlers.get(0).getPid() == mCreatorPid) &&
2649 (mScoAudioState == SCO_STATE_INACTIVE ||
2650 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
2651 if (mScoAudioState == SCO_STATE_INACTIVE) {
Eric Laurent83900752014-05-15 15:14:22 -07002652 mScoAudioMode = scoAudioMode;
Liejun Taof4e51d82014-07-16 11:18:29 -07002653 if (scoAudioMode == SCO_MODE_UNDEFINED) {
Andre Eisenbach570cc532014-10-28 17:03:18 -07002654 if (mBluetoothHeadsetDevice != null) {
2655 mScoAudioMode = new Integer(Settings.Global.getInt(
2656 mContentResolver,
2657 "bluetooth_sco_channel_"+
2658 mBluetoothHeadsetDevice.getAddress(),
2659 SCO_MODE_VIRTUAL_CALL));
2660 if (mScoAudioMode > SCO_MODE_MAX || mScoAudioMode < 0) {
2661 mScoAudioMode = SCO_MODE_VIRTUAL_CALL;
2662 }
2663 } else {
2664 mScoAudioMode = SCO_MODE_RAW;
Liejun Taof4e51d82014-07-16 11:18:29 -07002665 }
2666 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002667 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
Liejun Taof4e51d82014-07-16 11:18:29 -07002668 boolean status = false;
Eric Laurentc18c9132013-04-12 17:24:56 -07002669 if (mScoAudioMode == SCO_MODE_RAW) {
2670 status = mBluetoothHeadset.connectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002671 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002672 status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
2673 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002674 } else if (mScoAudioMode == SCO_MODE_VR) {
2675 status = mBluetoothHeadset.startVoiceRecognition(
2676 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002677 }
Liejun Taof4e51d82014-07-16 11:18:29 -07002678
Eric Laurentc18c9132013-04-12 17:24:56 -07002679 if (status) {
Eric Laurent9f103de2011-09-08 15:04:23 -07002680 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
2681 } else {
2682 broadcastScoConnectionState(
2683 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2684 }
2685 } else if (getBluetoothHeadset()) {
2686 mScoAudioState = SCO_STATE_ACTIVATE_REQ;
Eric Laurentdc03c612011-04-01 10:59:41 -07002687 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002688 } else {
2689 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
2690 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED);
Eric Laurentdc03c612011-04-01 10:59:41 -07002691 }
2692 } else {
Eric Laurent9f103de2011-09-08 15:04:23 -07002693 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
Eric Laurentdc03c612011-04-01 10:59:41 -07002694 }
Eric Laurentdc03c612011-04-01 10:59:41 -07002695 }
Eric Laurent62ef7672010-11-24 10:58:32 -08002696 } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED &&
Eric Laurentdc03c612011-04-01 10:59:41 -07002697 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
2698 mScoAudioState == SCO_STATE_ACTIVATE_REQ)) {
2699 if (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) {
Marco Nelissen671db6f2011-09-06 16:29:12 -07002700 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
Liejun Taof4e51d82014-07-16 11:18:29 -07002701 boolean status = false;
Eric Laurentc18c9132013-04-12 17:24:56 -07002702 if (mScoAudioMode == SCO_MODE_RAW) {
2703 status = mBluetoothHeadset.disconnectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002704 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002705 status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
2706 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002707 } else if (mScoAudioMode == SCO_MODE_VR) {
2708 status = mBluetoothHeadset.stopVoiceRecognition(
2709 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002710 }
Liejun Taof4e51d82014-07-16 11:18:29 -07002711
Eric Laurentc18c9132013-04-12 17:24:56 -07002712 if (!status) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002713 mScoAudioState = SCO_STATE_INACTIVE;
2714 broadcastScoConnectionState(
2715 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2716 }
2717 } else if (getBluetoothHeadset()) {
2718 mScoAudioState = SCO_STATE_DEACTIVATE_REQ;
2719 }
2720 } else {
2721 mScoAudioState = SCO_STATE_INACTIVE;
2722 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2723 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002724 }
2725 }
2726 }
2727 }
2728
Eric Laurent62ef7672010-11-24 10:58:32 -08002729 private void checkScoAudioState() {
2730 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null &&
Eric Laurentdc03c612011-04-01 10:59:41 -07002731 mScoAudioState == SCO_STATE_INACTIVE &&
Eric Laurent62ef7672010-11-24 10:58:32 -08002732 mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice)
2733 != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
2734 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2735 }
2736 }
2737
Eric Laurent854938a2011-02-22 12:05:20 -08002738 private ScoClient getScoClient(IBinder cb, boolean create) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002739 synchronized(mScoClients) {
Eric Laurent854938a2011-02-22 12:05:20 -08002740 ScoClient client = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002741 int size = mScoClients.size();
2742 for (int i = 0; i < size; i++) {
2743 client = mScoClients.get(i);
2744 if (client.getBinder() == cb)
2745 return client;
2746 }
Eric Laurent854938a2011-02-22 12:05:20 -08002747 if (create) {
2748 client = new ScoClient(cb);
2749 mScoClients.add(client);
2750 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002751 return client;
2752 }
2753 }
2754
Eric Laurentd7454be2011-09-14 08:45:58 -07002755 public void clearAllScoClients(int exceptPid, boolean stopSco) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002756 synchronized(mScoClients) {
Eric Laurent854938a2011-02-22 12:05:20 -08002757 ScoClient savedClient = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002758 int size = mScoClients.size();
2759 for (int i = 0; i < size; i++) {
Eric Laurent854938a2011-02-22 12:05:20 -08002760 ScoClient cl = mScoClients.get(i);
Eric Laurentd7454be2011-09-14 08:45:58 -07002761 if (cl.getPid() != exceptPid) {
Eric Laurent854938a2011-02-22 12:05:20 -08002762 cl.clearCount(stopSco);
2763 } else {
2764 savedClient = cl;
2765 }
2766 }
2767 mScoClients.clear();
2768 if (savedClient != null) {
2769 mScoClients.add(savedClient);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002770 }
2771 }
2772 }
2773
Eric Laurentdc03c612011-04-01 10:59:41 -07002774 private boolean getBluetoothHeadset() {
2775 boolean result = false;
2776 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
2777 if (adapter != null) {
2778 result = adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
2779 BluetoothProfile.HEADSET);
2780 }
2781 // If we could not get a bluetooth headset proxy, send a failure message
2782 // without delay to reset the SCO audio state and clear SCO clients.
2783 // If we could get a proxy, send a delayed failure message that will reset our state
2784 // in case we don't receive onServiceConnected().
Eric Laurentafbb0472011-12-15 09:04:23 -08002785 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurentdc03c612011-04-01 10:59:41 -07002786 SENDMSG_REPLACE, 0, 0, null, result ? BT_HEADSET_CNCT_TIMEOUT_MS : 0);
2787 return result;
2788 }
2789
Eric Laurentd7454be2011-09-14 08:45:58 -07002790 private void disconnectBluetoothSco(int exceptPid) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002791 synchronized(mScoClients) {
2792 checkScoAudioState();
2793 if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL ||
2794 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
2795 if (mBluetoothHeadsetDevice != null) {
2796 if (mBluetoothHeadset != null) {
2797 if (!mBluetoothHeadset.stopVoiceRecognition(
Eric Laurentb06ac832011-05-25 15:55:18 -07002798 mBluetoothHeadsetDevice)) {
Eric Laurentafbb0472011-12-15 09:04:23 -08002799 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurentdc03c612011-04-01 10:59:41 -07002800 SENDMSG_REPLACE, 0, 0, null, 0);
2801 }
2802 } else if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL &&
2803 getBluetoothHeadset()) {
2804 mScoAudioState = SCO_STATE_DEACTIVATE_EXT_REQ;
2805 }
2806 }
2807 } else {
Eric Laurentd7454be2011-09-14 08:45:58 -07002808 clearAllScoClients(exceptPid, true);
Eric Laurentdc03c612011-04-01 10:59:41 -07002809 }
2810 }
2811 }
2812
2813 private void resetBluetoothSco() {
2814 synchronized(mScoClients) {
Eric Laurentd7454be2011-09-14 08:45:58 -07002815 clearAllScoClients(0, false);
Eric Laurentdc03c612011-04-01 10:59:41 -07002816 mScoAudioState = SCO_STATE_INACTIVE;
2817 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2818 }
2819 }
2820
2821 private void broadcastScoConnectionState(int state) {
Eric Laurent2a57ca92013-03-07 17:29:27 -08002822 sendMsg(mAudioHandler, MSG_BROADCAST_BT_CONNECTION_STATE,
2823 SENDMSG_QUEUE, state, 0, null, 0);
2824 }
2825
2826 private void onBroadcastScoConnectionState(int state) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002827 if (state != mScoConnectionState) {
2828 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
2829 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
2830 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE,
2831 mScoConnectionState);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002832 sendStickyBroadcastToAll(newIntent);
Eric Laurentdc03c612011-04-01 10:59:41 -07002833 mScoConnectionState = state;
2834 }
2835 }
2836
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07002837 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
2838 new BluetoothProfile.ServiceListener() {
2839 public void onServiceConnected(int profile, BluetoothProfile proxy) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002840 BluetoothDevice btDevice;
2841 List<BluetoothDevice> deviceList;
2842 switch(profile) {
2843 case BluetoothProfile.A2DP:
seunghwan.hong4fe77952014-10-29 17:43:20 +09002844 synchronized (mConnectedDevices) {
2845 synchronized (mA2dpAvrcpLock) {
2846 mA2dp = (BluetoothA2dp) proxy;
2847 deviceList = mA2dp.getConnectedDevices();
2848 if (deviceList.size() > 0) {
2849 btDevice = deviceList.get(0);
John Du5a0cf7a2013-07-19 11:30:34 -07002850 int state = mA2dp.getConnectionState(btDevice);
2851 int delay = checkSendBecomingNoisyIntent(
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002852 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2853 (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
John Du5a0cf7a2013-07-19 11:30:34 -07002854 queueMsgUnderWakeLock(mAudioHandler,
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002855 MSG_SET_A2DP_SINK_CONNECTION_STATE,
John Du5a0cf7a2013-07-19 11:30:34 -07002856 state,
2857 0,
2858 btDevice,
2859 delay);
2860 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07002861 }
Eric Laurent62ef7672010-11-24 10:58:32 -08002862 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002863 break;
2864
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002865 case BluetoothProfile.A2DP_SINK:
2866 deviceList = proxy.getConnectedDevices();
2867 if (deviceList.size() > 0) {
2868 btDevice = deviceList.get(0);
2869 synchronized (mConnectedDevices) {
2870 int state = proxy.getConnectionState(btDevice);
2871 queueMsgUnderWakeLock(mAudioHandler,
2872 MSG_SET_A2DP_SRC_CONNECTION_STATE,
2873 state,
2874 0,
2875 btDevice,
2876 0 /* delay */);
2877 }
2878 }
2879 break;
2880
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002881 case BluetoothProfile.HEADSET:
2882 synchronized (mScoClients) {
2883 // Discard timeout message
2884 mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED);
2885 mBluetoothHeadset = (BluetoothHeadset) proxy;
2886 deviceList = mBluetoothHeadset.getConnectedDevices();
2887 if (deviceList.size() > 0) {
2888 mBluetoothHeadsetDevice = deviceList.get(0);
2889 } else {
2890 mBluetoothHeadsetDevice = null;
2891 }
2892 // Refresh SCO audio state
2893 checkScoAudioState();
2894 // Continue pending action if any
2895 if (mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
2896 mScoAudioState == SCO_STATE_DEACTIVATE_REQ ||
2897 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
2898 boolean status = false;
2899 if (mBluetoothHeadsetDevice != null) {
2900 switch (mScoAudioState) {
2901 case SCO_STATE_ACTIVATE_REQ:
2902 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
Eric Laurentc18c9132013-04-12 17:24:56 -07002903 if (mScoAudioMode == SCO_MODE_RAW) {
2904 status = mBluetoothHeadset.connectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002905 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002906 status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
2907 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002908 } else if (mScoAudioMode == SCO_MODE_VR) {
2909 status = mBluetoothHeadset.startVoiceRecognition(
2910 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002911 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002912 break;
2913 case SCO_STATE_DEACTIVATE_REQ:
Eric Laurentc18c9132013-04-12 17:24:56 -07002914 if (mScoAudioMode == SCO_MODE_RAW) {
2915 status = mBluetoothHeadset.disconnectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002916 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002917 status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
2918 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002919 } else if (mScoAudioMode == SCO_MODE_VR) {
2920 status = mBluetoothHeadset.stopVoiceRecognition(
2921 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002922 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002923 break;
2924 case SCO_STATE_DEACTIVATE_EXT_REQ:
2925 status = mBluetoothHeadset.stopVoiceRecognition(
2926 mBluetoothHeadsetDevice);
2927 }
2928 }
2929 if (!status) {
Eric Laurentafbb0472011-12-15 09:04:23 -08002930 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002931 SENDMSG_REPLACE, 0, 0, null, 0);
Eric Laurentdc03c612011-04-01 10:59:41 -07002932 }
2933 }
Eric Laurentdc03c612011-04-01 10:59:41 -07002934 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002935 break;
2936
2937 default:
2938 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002939 }
2940 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07002941 public void onServiceDisconnected(int profile) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002942 switch(profile) {
2943 case BluetoothProfile.A2DP:
seunghwan.hong4fe77952014-10-29 17:43:20 +09002944 synchronized (mConnectedDevices) {
2945 synchronized (mA2dpAvrcpLock) {
2946 mA2dp = null;
John Du5a0cf7a2013-07-19 11:30:34 -07002947 if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) {
2948 makeA2dpDeviceUnavailableNow(
2949 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP));
2950 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002951 }
2952 }
2953 break;
2954
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002955 case BluetoothProfile.A2DP_SINK:
2956 synchronized (mConnectedDevices) {
2957 if (mConnectedDevices.containsKey(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP)) {
2958 makeA2dpSrcUnavailable(
2959 mConnectedDevices.get(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP));
2960 }
2961 }
2962 break;
2963
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002964 case BluetoothProfile.HEADSET:
2965 synchronized (mScoClients) {
2966 mBluetoothHeadset = null;
2967 }
2968 break;
2969
2970 default:
2971 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002972 }
2973 }
2974 };
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002975
Eric Laurentc34dcc12012-09-10 13:51:52 -07002976 private void onCheckMusicActive() {
Eric Laurentd640bd32012-09-28 18:01:48 -07002977 synchronized (mSafeMediaVolumeState) {
2978 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07002979 int device = getDeviceForStream(AudioSystem.STREAM_MUSIC);
2980
2981 if ((device & mSafeMediaVolumeDevices) != 0) {
2982 sendMsg(mAudioHandler,
2983 MSG_CHECK_MUSIC_ACTIVE,
2984 SENDMSG_REPLACE,
Eric Laurentf1a457d2012-09-20 16:27:23 -07002985 0,
Eric Laurentc34dcc12012-09-10 13:51:52 -07002986 0,
2987 null,
2988 MUSIC_ACTIVE_POLL_PERIOD_MS);
Eric Laurent42b041e2013-03-29 11:36:03 -07002989 int index = mStreamStates[AudioSystem.STREAM_MUSIC].getIndex(device);
Eric Laurentf1a457d2012-09-20 16:27:23 -07002990 if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0) &&
2991 (index > mSafeMediaVolumeIndex)) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07002992 // Approximate cumulative active music time
2993 mMusicActiveMs += MUSIC_ACTIVE_POLL_PERIOD_MS;
2994 if (mMusicActiveMs > UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX) {
2995 setSafeMediaVolumeEnabled(true);
2996 mMusicActiveMs = 0;
Eric Laurentc34dcc12012-09-10 13:51:52 -07002997 }
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002998 saveMusicActiveMs();
Eric Laurentc34dcc12012-09-10 13:51:52 -07002999 }
3000 }
3001 }
3002 }
3003 }
3004
John Spurlockaa5ee4d2014-07-25 13:05:12 -04003005 private void saveMusicActiveMs() {
3006 mAudioHandler.obtainMessage(MSG_PERSIST_MUSIC_ACTIVE_MS, mMusicActiveMs, 0).sendToTarget();
3007 }
3008
Eric Laurentd640bd32012-09-28 18:01:48 -07003009 private void onConfigureSafeVolume(boolean force) {
3010 synchronized (mSafeMediaVolumeState) {
3011 int mcc = mContext.getResources().getConfiguration().mcc;
3012 if ((mMcc != mcc) || ((mMcc == 0) && force)) {
3013 mSafeMediaVolumeIndex = mContext.getResources().getInteger(
3014 com.android.internal.R.integer.config_safe_media_volume_index) * 10;
John Spurlock35134602014-07-24 18:10:48 -04003015 boolean safeMediaVolumeEnabled =
3016 SystemProperties.getBoolean("audio.safemedia.force", false)
3017 || mContext.getResources().getBoolean(
3018 com.android.internal.R.bool.config_safe_media_volume_enabled);
Eric Laurent05274f32012-11-29 12:48:18 -08003019
3020 // The persisted state is either "disabled" or "active": this is the state applied
3021 // next time we boot and cannot be "inactive"
3022 int persistedState;
Eric Laurentd640bd32012-09-28 18:01:48 -07003023 if (safeMediaVolumeEnabled) {
Eric Laurent05274f32012-11-29 12:48:18 -08003024 persistedState = SAFE_MEDIA_VOLUME_ACTIVE;
3025 // The state can already be "inactive" here if the user has forced it before
3026 // the 30 seconds timeout for forced configuration. In this case we don't reset
3027 // it to "active".
3028 if (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_INACTIVE) {
John Spurlockaa5ee4d2014-07-25 13:05:12 -04003029 if (mMusicActiveMs == 0) {
3030 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE;
3031 enforceSafeMediaVolume();
3032 } else {
3033 // We have existing playback time recorded, already confirmed.
3034 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE;
3035 }
Eric Laurent05274f32012-11-29 12:48:18 -08003036 }
Eric Laurentd640bd32012-09-28 18:01:48 -07003037 } else {
Eric Laurent05274f32012-11-29 12:48:18 -08003038 persistedState = SAFE_MEDIA_VOLUME_DISABLED;
Eric Laurentd640bd32012-09-28 18:01:48 -07003039 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_DISABLED;
3040 }
3041 mMcc = mcc;
Eric Laurent05274f32012-11-29 12:48:18 -08003042 sendMsg(mAudioHandler,
3043 MSG_PERSIST_SAFE_VOLUME_STATE,
3044 SENDMSG_QUEUE,
3045 persistedState,
3046 0,
3047 null,
3048 0);
Eric Laurentd640bd32012-09-28 18:01:48 -07003049 }
3050 }
3051 }
3052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 ///////////////////////////////////////////////////////////////////////////
3054 // Internal methods
3055 ///////////////////////////////////////////////////////////////////////////
3056
3057 /**
3058 * Checks if the adjustment should change ringer mode instead of just
3059 * adjusting volume. If so, this will set the proper ringer mode and volume
3060 * indices on the stream states.
3061 */
RoboErik5452e252015-02-06 15:33:53 -08003062 private int checkForRingerModeChange(int oldIndex, int direction, int step, boolean isMuted) {
John Spurlocka11b4af2014-06-01 11:52:23 -04003063 int result = FLAG_ADJUST_VOLUME;
John Spurlock661f2cf2014-11-17 10:29:10 -05003064 int ringerMode = getRingerModeInternal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065
Eric Laurentbffc3d12012-05-07 17:43:49 -07003066 switch (ringerMode) {
3067 case RINGER_MODE_NORMAL:
3068 if (direction == AudioManager.ADJUST_LOWER) {
3069 if (mHasVibrator) {
Eric Laurent24482012012-05-10 09:41:17 -07003070 // "step" is the delta in internal index units corresponding to a
3071 // change of 1 in UI index units.
3072 // Because of rounding when rescaling from one stream index range to its alias
3073 // index range, we cannot simply test oldIndex == step:
3074 // (step <= oldIndex < 2 * step) is equivalent to: (old UI index == 1)
3075 if (step <= oldIndex && oldIndex < 2 * step) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07003076 ringerMode = RINGER_MODE_VIBRATE;
3077 }
3078 } else {
Eric Laurent24482012012-05-10 09:41:17 -07003079 // (oldIndex < step) is equivalent to (old UI index == 0)
John Spurlock86005342014-05-23 11:58:00 -04003080 if ((oldIndex < step)
3081 && VOLUME_SETS_RINGER_MODE_SILENT
3082 && mPrevVolDirection != AudioManager.ADJUST_LOWER) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07003083 ringerMode = RINGER_MODE_SILENT;
3084 }
Eric Laurent3d4c06f2011-08-15 19:58:28 -07003085 }
RoboErik5452e252015-02-06 15:33:53 -08003086 } else if (direction == AudioManager.ADJUST_TOGGLE_MUTE
3087 || direction == AudioManager.ADJUST_MUTE) {
3088 if (mHasVibrator) {
3089 ringerMode = RINGER_MODE_VIBRATE;
3090 } else {
3091 ringerMode = RINGER_MODE_SILENT;
3092 }
3093 // Setting the ringer mode will toggle mute
3094 result &= ~FLAG_ADJUST_VOLUME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003096 break;
3097 case RINGER_MODE_VIBRATE:
3098 if (!mHasVibrator) {
3099 Log.e(TAG, "checkForRingerModeChange() current ringer mode is vibrate" +
3100 "but no vibrator is present");
3101 break;
3102 }
Amith Yamasanic696a532011-10-28 17:02:37 -07003103 if ((direction == AudioManager.ADJUST_LOWER)) {
RoboErik5452e252015-02-06 15:33:53 -08003104 // This is the case we were muted with the volume turned up
3105 if (oldIndex >= 2 * step && isMuted) {
3106 ringerMode = RINGER_MODE_NORMAL;
3107 } else if (mPrevVolDirection != AudioManager.ADJUST_LOWER) {
John Spurlock795a5142014-12-08 14:09:35 -05003108 if (VOLUME_SETS_RINGER_MODE_SILENT) {
3109 ringerMode = RINGER_MODE_SILENT;
3110 } else {
3111 result |= AudioManager.FLAG_SHOW_VIBRATE_HINT;
3112 }
Amith Yamasanic696a532011-10-28 17:02:37 -07003113 }
RoboErik5452e252015-02-06 15:33:53 -08003114 } else if (direction == AudioManager.ADJUST_RAISE
3115 || direction == AudioManager.ADJUST_TOGGLE_MUTE
3116 || direction == AudioManager.ADJUST_UNMUTE) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07003117 ringerMode = RINGER_MODE_NORMAL;
Amith Yamasanic696a532011-10-28 17:02:37 -07003118 }
John Spurlocka11b4af2014-06-01 11:52:23 -04003119 result &= ~FLAG_ADJUST_VOLUME;
Eric Laurentbffc3d12012-05-07 17:43:49 -07003120 break;
3121 case RINGER_MODE_SILENT:
RoboErik5452e252015-02-06 15:33:53 -08003122 if (direction == AudioManager.ADJUST_LOWER && oldIndex >= 2 * step && isMuted) {
3123 // This is the case we were muted with the volume turned up
3124 ringerMode = RINGER_MODE_NORMAL;
3125 } else if (direction == AudioManager.ADJUST_RAISE
3126 || direction == AudioManager.ADJUST_TOGGLE_MUTE
3127 || direction == AudioManager.ADJUST_UNMUTE) {
John Spurlocka11b4af2014-06-01 11:52:23 -04003128 if (PREVENT_VOLUME_ADJUSTMENT_IF_SILENT) {
3129 result |= AudioManager.FLAG_SHOW_SILENT_HINT;
Eric Laurentbffc3d12012-05-07 17:43:49 -07003130 } else {
RoboErik5452e252015-02-06 15:33:53 -08003131 if (mHasVibrator && direction == AudioManager.ADJUST_RAISE) {
John Spurlocka11b4af2014-06-01 11:52:23 -04003132 ringerMode = RINGER_MODE_VIBRATE;
3133 } else {
RoboErik5452e252015-02-06 15:33:53 -08003134 // If we don't have a vibrator or they were toggling mute
3135 // go straight back to normal.
John Spurlocka11b4af2014-06-01 11:52:23 -04003136 ringerMode = RINGER_MODE_NORMAL;
3137 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003138 }
Daniel Sandler6329bf72010-02-26 15:17:44 -05003139 }
John Spurlocka11b4af2014-06-01 11:52:23 -04003140 result &= ~FLAG_ADJUST_VOLUME;
Eric Laurentbffc3d12012-05-07 17:43:49 -07003141 break;
3142 default:
3143 Log.e(TAG, "checkForRingerModeChange() wrong ringer mode: "+ringerMode);
3144 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
3146
John Spurlock661f2cf2014-11-17 10:29:10 -05003147 setRingerMode(ringerMode, TAG + ".checkForRingerModeChange", false /*external*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148
Eric Laurent25101b02011-02-02 09:33:30 -08003149 mPrevVolDirection = direction;
3150
John Spurlocka11b4af2014-06-01 11:52:23 -04003151 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 }
3153
John Spurlock3346a802014-05-20 16:25:37 -04003154 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 public boolean isStreamAffectedByRingerMode(int streamType) {
Eric Laurent9bcf4012009-06-12 06:09:28 -07003156 return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 }
3158
Eric Laurent5b4e6542010-03-19 20:02:21 -07003159 private boolean isStreamMutedByRingerMode(int streamType) {
3160 return (mRingerModeMutedStreams & (1 << streamType)) != 0;
3161 }
3162
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003163 boolean updateRingerModeAffectedStreams() {
3164 int ringerModeAffectedStreams;
3165 // make sure settings for ringer mode are consistent with device type: non voice capable
3166 // devices (tablets) include media stream in silent mode whereas phones don't.
3167 ringerModeAffectedStreams = Settings.System.getIntForUser(mContentResolver,
3168 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
3169 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
3170 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)),
3171 UserHandle.USER_CURRENT);
3172
3173 // ringtone, notification and system streams are always affected by ringer mode
3174 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_RING)|
3175 (1 << AudioSystem.STREAM_NOTIFICATION)|
3176 (1 << AudioSystem.STREAM_SYSTEM);
3177
Eric Laurent212532b2014-07-21 15:43:18 -07003178 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -05003179 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -07003180 ringerModeAffectedStreams = 0;
3181 break;
3182 default:
John Spurlock77e54d92014-08-11 12:16:24 -04003183 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
Eric Laurent212532b2014-07-21 15:43:18 -07003184 break;
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003185 }
Eric Laurent212532b2014-07-21 15:43:18 -07003186
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003187 synchronized (mCameraSoundForced) {
3188 if (mCameraSoundForced) {
3189 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
3190 } else {
3191 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
3192 }
3193 }
3194 if (mStreamVolumeAlias[AudioSystem.STREAM_DTMF] == AudioSystem.STREAM_RING) {
3195 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_DTMF);
3196 } else {
3197 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_DTMF);
3198 }
3199
3200 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
3201 Settings.System.putIntForUser(mContentResolver,
3202 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
3203 ringerModeAffectedStreams,
3204 UserHandle.USER_CURRENT);
3205 mRingerModeAffectedStreams = ringerModeAffectedStreams;
3206 return true;
3207 }
3208 return false;
3209 }
3210
John Spurlocka9dfbe8b2015-02-17 11:01:51 -05003211 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 public boolean isStreamAffectedByMute(int streamType) {
3213 return (mMuteAffectedStreams & (1 << streamType)) != 0;
3214 }
3215
3216 private void ensureValidDirection(int direction) {
RoboErik4197cb62015-01-21 15:45:32 -08003217 switch (direction) {
3218 case AudioManager.ADJUST_LOWER:
3219 case AudioManager.ADJUST_RAISE:
3220 case AudioManager.ADJUST_SAME:
3221 case AudioManager.ADJUST_MUTE:
3222 case AudioManager.ADJUST_UNMUTE:
3223 case AudioManager.ADJUST_TOGGLE_MUTE:
3224 break;
3225 default:
3226 throw new IllegalArgumentException("Bad direction " + direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 }
3228 }
3229
Lei Zhang6c798972012-03-02 11:40:12 -08003230 private void ensureValidSteps(int steps) {
3231 if (Math.abs(steps) > MAX_BATCH_VOLUME_ADJUST_STEPS) {
3232 throw new IllegalArgumentException("Bad volume adjust steps " + steps);
3233 }
3234 }
3235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 private void ensureValidStreamType(int streamType) {
3237 if (streamType < 0 || streamType >= mStreamStates.length) {
3238 throw new IllegalArgumentException("Bad stream type " + streamType);
3239 }
3240 }
3241
RoboErik4197cb62015-01-21 15:45:32 -08003242 private boolean isMuteAdjust(int adjust) {
3243 return adjust == AudioManager.ADJUST_MUTE || adjust == AudioManager.ADJUST_UNMUTE
3244 || adjust == AudioManager.ADJUST_TOGGLE_MUTE;
3245 }
3246
Eric Laurent6d517662012-04-23 18:42:39 -07003247 private boolean isInCommunication() {
Nancy Chen0eb1e402014-08-21 22:52:29 -07003248 boolean IsInCall = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249
Tyler Gunnef9f6f92014-09-12 22:16:17 -07003250 TelecomManager telecomManager =
3251 (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
Eric Laurent38edfda2014-12-18 17:38:04 -08003252
3253 final long ident = Binder.clearCallingIdentity();
Tyler Gunnef9f6f92014-09-12 22:16:17 -07003254 IsInCall = telecomManager.isInCall();
Eric Laurent38edfda2014-12-18 17:38:04 -08003255 Binder.restoreCallingIdentity(ident);
Santos Cordon9eb45932014-06-27 12:28:43 -07003256
Nancy Chen0eb1e402014-08-21 22:52:29 -07003257 return (IsInCall || getMode() == AudioManager.MODE_IN_COMMUNICATION);
Eric Laurent6d517662012-04-23 18:42:39 -07003258 }
Eric Laurent25101b02011-02-02 09:33:30 -08003259
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003260 /**
3261 * For code clarity for getActiveStreamType(int)
3262 * @param delay_ms max time since last STREAM_MUSIC activity to consider
3263 * @return true if STREAM_MUSIC is active in streams handled by AudioFlinger now or
3264 * in the last "delay_ms" ms.
3265 */
3266 private boolean isAfMusicActiveRecently(int delay_ms) {
3267 return AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, delay_ms)
3268 || AudioSystem.isStreamActiveRemotely(AudioSystem.STREAM_MUSIC, delay_ms);
3269 }
3270
Eric Laurent6d517662012-04-23 18:42:39 -07003271 private int getActiveStreamType(int suggestedStreamType) {
Eric Laurent212532b2014-07-21 15:43:18 -07003272 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -05003273 case AudioSystem.PLATFORM_VOICE:
Eric Laurent6d517662012-04-23 18:42:39 -07003274 if (isInCommunication()) {
Eric Laurent25101b02011-02-02 09:33:30 -08003275 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
3276 == AudioSystem.FORCE_BT_SCO) {
3277 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
3278 return AudioSystem.STREAM_BLUETOOTH_SCO;
3279 } else {
3280 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
3281 return AudioSystem.STREAM_VOICE_CALL;
3282 }
Eric Laurent25101b02011-02-02 09:33:30 -08003283 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003284 if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003285 if (DEBUG_VOL)
3286 Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
3287 return AudioSystem.STREAM_MUSIC;
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003288 } else {
3289 if (DEBUG_VOL)
3290 Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING b/c default");
3291 return AudioSystem.STREAM_RING;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003292 }
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003293 } else if (isAfMusicActiveRecently(0)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003294 if (DEBUG_VOL)
3295 Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
3296 return AudioSystem.STREAM_MUSIC;
Eric Laurent25101b02011-02-02 09:33:30 -08003297 }
Eric Laurent212532b2014-07-21 15:43:18 -07003298 break;
John Spurlock61560172015-02-06 19:46:04 -05003299 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -07003300 if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
RoboErik2811dd32014-08-12 09:48:13 -07003301 // TV always defaults to STREAM_MUSIC
Eric Laurent212532b2014-07-21 15:43:18 -07003302 return AudioSystem.STREAM_MUSIC;
Eric Laurent212532b2014-07-21 15:43:18 -07003303 }
3304 break;
3305 default:
Eric Laurent6d517662012-04-23 18:42:39 -07003306 if (isInCommunication()) {
Eric Laurent25101b02011-02-02 09:33:30 -08003307 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
3308 == AudioSystem.FORCE_BT_SCO) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003309 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO");
Eric Laurent25101b02011-02-02 09:33:30 -08003310 return AudioSystem.STREAM_BLUETOOTH_SCO;
3311 } else {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003312 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL");
Eric Laurent25101b02011-02-02 09:33:30 -08003313 return AudioSystem.STREAM_VOICE_CALL;
3314 }
3315 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003316 StreamOverride.sDelayMs) ||
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003317 AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003318 StreamOverride.sDelayMs)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003319 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION");
Eric Laurent25101b02011-02-02 09:33:30 -08003320 return AudioSystem.STREAM_NOTIFICATION;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003321 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003322 if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003323 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: forcing STREAM_MUSIC");
3324 return AudioSystem.STREAM_MUSIC;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003325 } else {
John Spurlockeb1d88d2014-07-19 14:49:19 -04003326 if (DEBUG_VOL) Log.v(TAG,
3327 "getActiveStreamType: using STREAM_NOTIFICATION as default");
3328 return AudioSystem.STREAM_NOTIFICATION;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003329 }
Joe Onoratoc7fcba42011-01-05 16:53:11 -08003330 }
Eric Laurent212532b2014-07-21 15:43:18 -07003331 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 }
Eric Laurent212532b2014-07-21 15:43:18 -07003333 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Returning suggested type "
3334 + suggestedStreamType);
3335 return suggestedStreamType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 }
3337
John Spurlockbcc10872014-11-28 15:29:21 -05003338 private void broadcastRingerMode(String action, int ringerMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 // Send sticky broadcast
John Spurlockbcc10872014-11-28 15:29:21 -05003340 Intent broadcast = new Intent(action);
Glenn Kastenba195eb2011-12-13 09:30:40 -08003341 broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, ringerMode);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08003342 broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
3343 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003344 sendStickyBroadcastToAll(broadcast);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
3346
3347 private void broadcastVibrateSetting(int vibrateType) {
3348 // Send broadcast
3349 if (ActivityManagerNative.isSystemReady()) {
3350 Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
3351 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
3352 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003353 sendBroadcastToAll(broadcast);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
3355 }
3356
3357 // Message helper methods
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003358 /**
3359 * Queue a message on the given handler's message queue, after acquiring the service wake lock.
3360 * Note that the wake lock needs to be released after the message has been handled.
3361 */
3362 private void queueMsgUnderWakeLock(Handler handler, int msg,
3363 int arg1, int arg2, Object obj, int delay) {
Eric Laurenta4dfbdc52013-10-01 11:53:51 -07003364 final long ident = Binder.clearCallingIdentity();
3365 // Always acquire the wake lock as AudioService because it is released by the
3366 // message handler.
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07003367 mAudioEventWakeLock.acquire();
Eric Laurenta4dfbdc52013-10-01 11:53:51 -07003368 Binder.restoreCallingIdentity(ident);
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003369 sendMsg(handler, msg, SENDMSG_QUEUE, arg1, arg2, obj, delay);
3370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371
Eric Laurentafbb0472011-12-15 09:04:23 -08003372 private static void sendMsg(Handler handler, int msg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374
3375 if (existingMsgPolicy == SENDMSG_REPLACE) {
3376 handler.removeMessages(msg);
3377 } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
3378 return;
3379 }
Eric Laurentadbe8bf2014-11-03 18:26:32 -08003380 synchronized (mLastDeviceConnectMsgTime) {
3381 long time = SystemClock.uptimeMillis() + delay;
3382 handler.sendMessageAtTime(handler.obtainMessage(msg, arg1, arg2, obj), time);
3383 if (msg == MSG_SET_WIRED_DEVICE_CONNECTION_STATE ||
3384 msg == MSG_SET_A2DP_SRC_CONNECTION_STATE ||
3385 msg == MSG_SET_A2DP_SINK_CONNECTION_STATE) {
3386 mLastDeviceConnectMsgTime = time;
3387 }
3388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 }
3390
3391 boolean checkAudioSettingsPermission(String method) {
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07003392 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 == PackageManager.PERMISSION_GRANTED) {
3394 return true;
3395 }
3396 String msg = "Audio Settings Permission Denial: " + method + " from pid="
3397 + Binder.getCallingPid()
3398 + ", uid=" + Binder.getCallingUid();
3399 Log.w(TAG, msg);
3400 return false;
3401 }
3402
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003403 private int getDeviceForStream(int stream) {
3404 int device = AudioSystem.getDevicesForStream(stream);
3405 if ((device & (device - 1)) != 0) {
3406 // Multiple device selection is either:
3407 // - speaker + one other device: give priority to speaker in this case.
3408 // - one A2DP device + another device: happens with duplicated output. In this case
3409 // retain the device on the A2DP output as the other must not correspond to an active
3410 // selection if not the speaker.
Jungshik Jangc9ff9682014-09-15 17:41:06 +09003411 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003412 if ((device & AudioSystem.DEVICE_OUT_SPEAKER) != 0) {
3413 device = AudioSystem.DEVICE_OUT_SPEAKER;
Jungshik Jangc9ff9682014-09-15 17:41:06 +09003414 } else if ((device & AudioSystem.DEVICE_OUT_HDMI_ARC) != 0) {
3415 device = AudioSystem.DEVICE_OUT_HDMI_ARC;
3416 } else if ((device & AudioSystem.DEVICE_OUT_SPDIF) != 0) {
3417 device = AudioSystem.DEVICE_OUT_SPDIF;
3418 } else if ((device & AudioSystem.DEVICE_OUT_AUX_LINE) != 0) {
3419 device = AudioSystem.DEVICE_OUT_AUX_LINE;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003420 } else {
3421 device &= AudioSystem.DEVICE_OUT_ALL_A2DP;
3422 }
3423 }
3424 return device;
3425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426
Paul McLean10804eb2015-01-28 11:16:35 -08003427 /*
3428 * A class just for packaging up a set of connection parameters.
3429 */
3430 private class WiredDeviceConnectionState {
3431 public int mType;
3432 public int mState;
3433 public String mAddress;
3434 public String mName;
3435
3436 public WiredDeviceConnectionState(int type, int state, String address, String name) {
3437 mType = type;
3438 mState = state;
3439 mAddress = address;
3440 mName = name;
3441 }
3442 }
3443
3444 public void setWiredDeviceConnectionState(int type, int state, String address,
3445 String name) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003446 synchronized (mConnectedDevices) {
Paul McLean10804eb2015-01-28 11:16:35 -08003447 int delay = checkSendBecomingNoisyIntent(type, state);
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003448 queueMsgUnderWakeLock(mAudioHandler,
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003449 MSG_SET_WIRED_DEVICE_CONNECTION_STATE,
Paul McLean10804eb2015-01-28 11:16:35 -08003450 0,
3451 0,
3452 new WiredDeviceConnectionState(type, state, address, name),
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003453 delay);
3454 }
3455 }
3456
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003457 public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state, int profile)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003458 {
3459 int delay;
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003460 if (profile != BluetoothProfile.A2DP && profile != BluetoothProfile.A2DP_SINK) {
3461 throw new IllegalArgumentException("invalid profile " + profile);
3462 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003463 synchronized (mConnectedDevices) {
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003464 if (profile == BluetoothProfile.A2DP) {
3465 delay = checkSendBecomingNoisyIntent(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
3466 (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
3467 } else {
3468 delay = 0;
3469 }
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003470 queueMsgUnderWakeLock(mAudioHandler,
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003471 (profile == BluetoothProfile.A2DP ?
3472 MSG_SET_A2DP_SINK_CONNECTION_STATE : MSG_SET_A2DP_SRC_CONNECTION_STATE),
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003473 state,
3474 0,
3475 device,
3476 delay);
3477 }
3478 return delay;
3479 }
3480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 ///////////////////////////////////////////////////////////////////////////
3482 // Inner classes
3483 ///////////////////////////////////////////////////////////////////////////
3484
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003485 // NOTE: Locking order for synchronized objects related to volume or ringer mode management:
3486 // 1 mScoclient OR mSafeMediaVolumeState
3487 // 2 mSetModeDeathHandlers
3488 // 3 mSettingsLock
3489 // 4 VolumeStreamState.class
3490 // 5 mCameraSoundForced
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 public class VolumeStreamState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 private final int mStreamType;
3493
RoboErik4197cb62015-01-21 15:45:32 -08003494 private boolean mIsMuted;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07003495 private String mVolumeIndexSettingName;
Eric Laurenta553c252009-07-17 12:17:14 -07003496 private int mIndexMax;
Eric Laurent3172d5e2012-05-09 11:38:16 -07003497 private final ConcurrentHashMap<Integer, Integer> mIndex =
3498 new ConcurrentHashMap<Integer, Integer>(8, 0.75f, 4);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499
Eric Laurenta553c252009-07-17 12:17:14 -07003500 private VolumeStreamState(String settingName, int streamType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003502 mVolumeIndexSettingName = settingName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503
3504 mStreamType = streamType;
Jared Suttles59820132009-08-13 21:50:52 -05003505 mIndexMax = MAX_STREAM_VOLUME[streamType];
Eric Laurenta553c252009-07-17 12:17:14 -07003506 AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
3507 mIndexMax *= 10;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003508
Eric Laurent33902db2012-10-07 16:15:07 -07003509 readSettings();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 }
3511
Eric Laurent42b041e2013-03-29 11:36:03 -07003512 public String getSettingNameForDevice(int device) {
3513 String name = mVolumeIndexSettingName;
Eric Laurent948d3272014-05-16 15:18:45 -07003514 String suffix = AudioSystem.getOutputDeviceName(device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003515 if (suffix.isEmpty()) {
3516 return name;
3517 }
3518 return name + "_" + suffix;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07003519 }
3520
Eric Laurentfdbee862014-05-12 15:26:12 -07003521 public void readSettings() {
3522 synchronized (VolumeStreamState.class) {
Wally Yauda392902014-11-28 12:40:30 -08003523 // force maximum volume on all streams if fixed volume property
3524 // or master volume property is set
3525 if (mUseFixedVolume || mUseMasterVolume) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003526 mIndex.put(AudioSystem.DEVICE_OUT_DEFAULT, mIndexMax);
3527 return;
3528 }
3529 // do not read system stream volume from settings: this stream is always aliased
3530 // to another stream type and its volume is never persisted. Values in settings can
3531 // only be stale values
3532 if ((mStreamType == AudioSystem.STREAM_SYSTEM) ||
3533 (mStreamType == AudioSystem.STREAM_SYSTEM_ENFORCED)) {
John Spurlock61560172015-02-06 19:46:04 -05003534 int index = 10 * AudioSystem.DEFAULT_STREAM_VOLUME[mStreamType];
Eric Laurentfdbee862014-05-12 15:26:12 -07003535 synchronized (mCameraSoundForced) {
3536 if (mCameraSoundForced) {
3537 index = mIndexMax;
3538 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003539 }
Eric Laurentfdbee862014-05-12 15:26:12 -07003540 mIndex.put(AudioSystem.DEVICE_OUT_DEFAULT, index);
3541 return;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003542 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003543
Eric Laurentfdbee862014-05-12 15:26:12 -07003544 int remainingDevices = AudioSystem.DEVICE_OUT_ALL;
3545
3546 for (int i = 0; remainingDevices != 0; i++) {
3547 int device = (1 << i);
3548 if ((device & remainingDevices) == 0) {
3549 continue;
3550 }
3551 remainingDevices &= ~device;
3552
3553 // retrieve current volume for device
3554 String name = getSettingNameForDevice(device);
3555 // if no volume stored for current stream and device, use default volume if default
3556 // device, continue otherwise
3557 int defaultIndex = (device == AudioSystem.DEVICE_OUT_DEFAULT) ?
John Spurlock61560172015-02-06 19:46:04 -05003558 AudioSystem.DEFAULT_STREAM_VOLUME[mStreamType] : -1;
Eric Laurentfdbee862014-05-12 15:26:12 -07003559 int index = Settings.System.getIntForUser(
3560 mContentResolver, name, defaultIndex, UserHandle.USER_CURRENT);
3561 if (index == -1) {
3562 continue;
3563 }
3564
Eric Laurent212532b2014-07-21 15:43:18 -07003565 mIndex.put(device, getValidIndex(10 * index));
Eric Laurentdd45d012012-10-08 09:04:34 -07003566 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003570 // must be called while synchronized VolumeStreamState.class
3571 public void applyDeviceVolume_syncVSS(int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003572 int index;
RoboErik4197cb62015-01-21 15:45:32 -08003573 if (mIsMuted) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003574 index = 0;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003575 } else if (((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 && mAvrcpAbsVolSupported)
3576 || ((device & mFullVolumeDevices) != 0)) {
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07003577 index = (mIndexMax + 5)/10;
Eric Laurentcd772d02013-10-30 18:31:07 -07003578 } else {
Eric Laurent42b041e2013-03-29 11:36:03 -07003579 index = (getIndex(device) + 5)/10;
3580 }
3581 AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583
Eric Laurentfdbee862014-05-12 15:26:12 -07003584 public void applyAllVolumes() {
3585 synchronized (VolumeStreamState.class) {
3586 // apply default volume first: by convention this will reset all
3587 // devices volumes in audio policy manager to the supplied value
3588 int index;
RoboErik4197cb62015-01-21 15:45:32 -08003589 if (mIsMuted) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003590 index = 0;
3591 } else {
3592 index = (getIndex(AudioSystem.DEVICE_OUT_DEFAULT) + 5)/10;
3593 }
3594 AudioSystem.setStreamVolumeIndex(mStreamType, index, AudioSystem.DEVICE_OUT_DEFAULT);
3595 // then apply device specific volumes
3596 Set set = mIndex.entrySet();
3597 Iterator i = set.iterator();
3598 while (i.hasNext()) {
3599 Map.Entry entry = (Map.Entry)i.next();
3600 int device = ((Integer)entry.getKey()).intValue();
3601 if (device != AudioSystem.DEVICE_OUT_DEFAULT) {
RoboErik4197cb62015-01-21 15:45:32 -08003602 if (mIsMuted) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003603 index = 0;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003604 } else if (((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
3605 mAvrcpAbsVolSupported)
3606 || ((device & mFullVolumeDevices) != 0))
3607 {
Eric Laurentfdbee862014-05-12 15:26:12 -07003608 index = (mIndexMax + 5)/10;
3609 } else {
3610 index = ((Integer)entry.getValue() + 5)/10;
3611 }
3612 AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
Eric Laurent42b041e2013-03-29 11:36:03 -07003613 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003614 }
3615 }
3616 }
3617
3618 public boolean adjustIndex(int deltaIndex, int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003619 return setIndex(getIndex(device) + deltaIndex,
3620 device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003621 }
3622
Eric Laurentfdbee862014-05-12 15:26:12 -07003623 public boolean setIndex(int index, int device) {
3624 synchronized (VolumeStreamState.class) {
3625 int oldIndex = getIndex(device);
3626 index = getValidIndex(index);
3627 synchronized (mCameraSoundForced) {
3628 if ((mStreamType == AudioSystem.STREAM_SYSTEM_ENFORCED) && mCameraSoundForced) {
3629 index = mIndexMax;
Eric Laurenta553c252009-07-17 12:17:14 -07003630 }
3631 }
Eric Laurentfdbee862014-05-12 15:26:12 -07003632 mIndex.put(device, index);
3633
3634 if (oldIndex != index) {
3635 // Apply change to all streams using this one as alias
3636 // if changing volume of current device, also change volume of current
3637 // device on aliased stream
3638 boolean currentDevice = (device == getDeviceForStream(mStreamType));
3639 int numStreamTypes = AudioSystem.getNumStreamTypes();
3640 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3641 if (streamType != mStreamType &&
3642 mStreamVolumeAlias[streamType] == mStreamType) {
3643 int scaledIndex = rescaleIndex(index, mStreamType, streamType);
3644 mStreamStates[streamType].setIndex(scaledIndex,
3645 device);
3646 if (currentDevice) {
3647 mStreamStates[streamType].setIndex(scaledIndex,
3648 getDeviceForStream(streamType));
3649 }
3650 }
3651 }
3652 return true;
3653 } else {
3654 return false;
3655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 }
3657 }
3658
Eric Laurentfdbee862014-05-12 15:26:12 -07003659 public int getIndex(int device) {
3660 synchronized (VolumeStreamState.class) {
3661 Integer index = mIndex.get(device);
3662 if (index == null) {
3663 // there is always an entry for AudioSystem.DEVICE_OUT_DEFAULT
3664 index = mIndex.get(AudioSystem.DEVICE_OUT_DEFAULT);
3665 }
3666 return index.intValue();
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003667 }
Eric Laurent5b4e6542010-03-19 20:02:21 -07003668 }
3669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 public int getMaxIndex() {
Eric Laurenta553c252009-07-17 12:17:14 -07003671 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 }
3673
Eric Laurentfdbee862014-05-12 15:26:12 -07003674 public void setAllIndexes(VolumeStreamState srcStream) {
3675 synchronized (VolumeStreamState.class) {
3676 int srcStreamType = srcStream.getStreamType();
3677 // apply default device volume from source stream to all devices first in case
3678 // some devices are present in this stream state but not in source stream state
3679 int index = srcStream.getIndex(AudioSystem.DEVICE_OUT_DEFAULT);
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003680 index = rescaleIndex(index, srcStreamType, mStreamType);
Eric Laurentfdbee862014-05-12 15:26:12 -07003681 Set set = mIndex.entrySet();
3682 Iterator i = set.iterator();
3683 while (i.hasNext()) {
3684 Map.Entry entry = (Map.Entry)i.next();
3685 entry.setValue(index);
3686 }
3687 // Now apply actual volume for devices in source stream state
3688 set = srcStream.mIndex.entrySet();
3689 i = set.iterator();
3690 while (i.hasNext()) {
3691 Map.Entry entry = (Map.Entry)i.next();
3692 int device = ((Integer)entry.getKey()).intValue();
3693 index = ((Integer)entry.getValue()).intValue();
3694 index = rescaleIndex(index, srcStreamType, mStreamType);
Eric Laurent33902db2012-10-07 16:15:07 -07003695
Eric Laurentfdbee862014-05-12 15:26:12 -07003696 setIndex(index, device);
3697 }
Eric Laurent6d517662012-04-23 18:42:39 -07003698 }
3699 }
3700
Eric Laurentfdbee862014-05-12 15:26:12 -07003701 public void setAllIndexesToMax() {
3702 synchronized (VolumeStreamState.class) {
3703 Set set = mIndex.entrySet();
3704 Iterator i = set.iterator();
3705 while (i.hasNext()) {
3706 Map.Entry entry = (Map.Entry)i.next();
3707 entry.setValue(mIndexMax);
3708 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003709 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003710 }
3711
RoboErik4197cb62015-01-21 15:45:32 -08003712 public void mute(boolean state) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003713 synchronized (VolumeStreamState.class) {
RoboErik4197cb62015-01-21 15:45:32 -08003714 if (state != mIsMuted) {
3715 mIsMuted = state;
3716 // Set the new mute volume. This propagates the values to
3717 // the audio system, otherwise the volume won't be changed
3718 // at the lower level.
3719 sendMsg(mAudioHandler,
3720 MSG_SET_ALL_VOLUMES,
3721 SENDMSG_QUEUE,
3722 0,
3723 0,
3724 this, 0);
Eric Laurentfdbee862014-05-12 15:26:12 -07003725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 }
3728
Eric Laurent6d517662012-04-23 18:42:39 -07003729 public int getStreamType() {
3730 return mStreamType;
3731 }
3732
Eric Laurent212532b2014-07-21 15:43:18 -07003733 public void checkFixedVolumeDevices() {
3734 synchronized (VolumeStreamState.class) {
3735 // ignore settings for fixed volume devices: volume should always be at max or 0
3736 if (mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_MUSIC) {
3737 Set set = mIndex.entrySet();
3738 Iterator i = set.iterator();
3739 while (i.hasNext()) {
3740 Map.Entry entry = (Map.Entry)i.next();
3741 int device = ((Integer)entry.getKey()).intValue();
3742 int index = ((Integer)entry.getValue()).intValue();
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003743 if (((device & mFullVolumeDevices) != 0)
3744 || (((device & mFixedVolumeDevices) != 0) && index != 0)) {
Eric Laurent212532b2014-07-21 15:43:18 -07003745 entry.setValue(mIndexMax);
3746 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003747 applyDeviceVolume_syncVSS(device);
Eric Laurent212532b2014-07-21 15:43:18 -07003748 }
3749 }
3750 }
3751 }
3752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 private int getValidIndex(int index) {
3754 if (index < 0) {
3755 return 0;
Wally Yauda392902014-11-28 12:40:30 -08003756 } else if (mUseFixedVolume || mUseMasterVolume || index > mIndexMax) {
Eric Laurenta553c252009-07-17 12:17:14 -07003757 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 }
3759
3760 return index;
3761 }
3762
Eric Laurentbffc3d12012-05-07 17:43:49 -07003763 private void dump(PrintWriter pw) {
RoboErik4197cb62015-01-21 15:45:32 -08003764 pw.print(" Muted: ");
3765 pw.println(mIsMuted);
John Spurlock2b29bc42014-08-26 16:40:35 -04003766 pw.print(" Max: ");
3767 pw.println((mIndexMax + 5) / 10);
Eric Laurentbffc3d12012-05-07 17:43:49 -07003768 pw.print(" Current: ");
3769 Set set = mIndex.entrySet();
3770 Iterator i = set.iterator();
3771 while (i.hasNext()) {
3772 Map.Entry entry = (Map.Entry)i.next();
John Spurlock2b29bc42014-08-26 16:40:35 -04003773 final int device = (Integer) entry.getKey();
3774 pw.print(Integer.toHexString(device));
3775 final String deviceName = device == AudioSystem.DEVICE_OUT_DEFAULT ? "default"
3776 : AudioSystem.getOutputDeviceName(device);
3777 if (!deviceName.isEmpty()) {
3778 pw.print(" (");
3779 pw.print(deviceName);
3780 pw.print(")");
3781 }
3782 pw.print(": ");
3783 final int index = (((Integer) entry.getValue()) + 5) / 10;
3784 pw.print(index);
3785 if (i.hasNext()) {
3786 pw.print(", ");
3787 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003788 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 }
3791
3792 /** Thread that handles native AudioSystem control. */
3793 private class AudioSystemThread extends Thread {
3794 AudioSystemThread() {
3795 super("AudioService");
3796 }
3797
3798 @Override
3799 public void run() {
3800 // Set this thread up so the handler will work on it
3801 Looper.prepare();
3802
3803 synchronized(AudioService.this) {
3804 mAudioHandler = new AudioHandler();
3805
3806 // Notify that the handler has been created
3807 AudioService.this.notify();
3808 }
3809
3810 // Listen for volume change requests that are set by VolumePanel
3811 Looper.loop();
3812 }
3813 }
3814
3815 /** Handles internal volume messages in separate volume thread. */
3816 private class AudioHandler extends Handler {
3817
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003818 private void setDeviceVolume(VolumeStreamState streamState, int device) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003820 synchronized (VolumeStreamState.class) {
3821 // Apply volume
3822 streamState.applyDeviceVolume_syncVSS(device);
Eric Laurenta553c252009-07-17 12:17:14 -07003823
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003824 // Apply change to all streams using this one as alias
3825 int numStreamTypes = AudioSystem.getNumStreamTypes();
3826 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3827 if (streamType != streamState.mStreamType &&
3828 mStreamVolumeAlias[streamType] == streamState.mStreamType) {
3829 // Make sure volume is also maxed out on A2DP device for aliased stream
3830 // that may have a different device selected
3831 int streamDevice = getDeviceForStream(streamType);
3832 if ((device != streamDevice) && mAvrcpAbsVolSupported &&
3833 ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0)) {
3834 mStreamStates[streamType].applyDeviceVolume_syncVSS(device);
3835 }
3836 mStreamStates[streamType].applyDeviceVolume_syncVSS(streamDevice);
Eric Laurentcd772d02013-10-30 18:31:07 -07003837 }
Eric Laurenta553c252009-07-17 12:17:14 -07003838 }
3839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 // Post a persist volume msg
Eric Laurentafbb0472011-12-15 09:04:23 -08003841 sendMsg(mAudioHandler,
3842 MSG_PERSIST_VOLUME,
Eric Laurent98ad9b92012-02-15 17:21:37 -08003843 SENDMSG_QUEUE,
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003844 device,
Eric Laurent42b041e2013-03-29 11:36:03 -07003845 0,
Eric Laurentafbb0472011-12-15 09:04:23 -08003846 streamState,
3847 PERSIST_DELAY);
3848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
3850
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003851 private void setAllVolumes(VolumeStreamState streamState) {
3852
3853 // Apply volume
3854 streamState.applyAllVolumes();
3855
3856 // Apply change to all streams using this one as alias
3857 int numStreamTypes = AudioSystem.getNumStreamTypes();
3858 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3859 if (streamType != streamState.mStreamType &&
Eric Laurent6d517662012-04-23 18:42:39 -07003860 mStreamVolumeAlias[streamType] == streamState.mStreamType) {
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003861 mStreamStates[streamType].applyAllVolumes();
3862 }
3863 }
3864 }
3865
Eric Laurent42b041e2013-03-29 11:36:03 -07003866 private void persistVolume(VolumeStreamState streamState, int device) {
Eric Laurent83a017b2013-03-19 18:15:31 -07003867 if (mUseFixedVolume) {
3868 return;
3869 }
Eric Laurent212532b2014-07-21 15:43:18 -07003870 if (isPlatformTelevision() && (streamState.mStreamType != AudioSystem.STREAM_MUSIC)) {
3871 return;
3872 }
Eric Laurent42b041e2013-03-29 11:36:03 -07003873 System.putIntForUser(mContentResolver,
3874 streamState.getSettingNameForDevice(device),
3875 (streamState.getIndex(device) + 5)/ 10,
3876 UserHandle.USER_CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 }
3878
Glenn Kastenba195eb2011-12-13 09:30:40 -08003879 private void persistRingerMode(int ringerMode) {
Eric Laurent83a017b2013-03-19 18:15:31 -07003880 if (mUseFixedVolume) {
3881 return;
3882 }
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07003883 Settings.Global.putInt(mContentResolver, Settings.Global.MODE_RINGER, ringerMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 }
3885
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003886 private boolean onLoadSoundEffects() {
3887 int status;
3888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 synchronized (mSoundEffectsLock) {
Eric Laurent4a5eeb92014-05-06 10:49:04 -07003890 if (!mSystemReady) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003891 Log.w(TAG, "onLoadSoundEffects() called before boot complete");
3892 return false;
3893 }
3894
3895 if (mSoundPool != null) {
3896 return true;
3897 }
3898
3899 loadTouchSoundAssets();
3900
Jean-Michel Trivi55a30c42014-07-20 17:56:11 -07003901 mSoundPool = new SoundPool.Builder()
3902 .setMaxStreams(NUM_SOUNDPOOL_CHANNELS)
3903 .setAudioAttributes(new AudioAttributes.Builder()
3904 .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
3905 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
3906 .build())
3907 .build();
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003908 mSoundPoolCallBack = null;
3909 mSoundPoolListenerThread = new SoundPoolListenerThread();
3910 mSoundPoolListenerThread.start();
3911 int attempts = 3;
3912 while ((mSoundPoolCallBack == null) && (attempts-- > 0)) {
3913 try {
3914 // Wait for mSoundPoolCallBack to be set by the other thread
Glenn Kasten167d1a22013-07-23 16:24:41 -07003915 mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003916 } catch (InterruptedException e) {
3917 Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
3918 }
3919 }
3920
3921 if (mSoundPoolCallBack == null) {
3922 Log.w(TAG, "onLoadSoundEffects() SoundPool listener or thread creation error");
3923 if (mSoundPoolLooper != null) {
3924 mSoundPoolLooper.quit();
3925 mSoundPoolLooper = null;
3926 }
3927 mSoundPoolListenerThread = null;
3928 mSoundPool.release();
3929 mSoundPool = null;
3930 return false;
3931 }
3932 /*
3933 * poolId table: The value -1 in this table indicates that corresponding
3934 * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
3935 * Once loaded, the value in poolId is the sample ID and the same
3936 * sample can be reused for another effect using the same file.
3937 */
3938 int[] poolId = new int[SOUND_EFFECT_FILES.size()];
3939 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.size(); fileIdx++) {
3940 poolId[fileIdx] = -1;
3941 }
3942 /*
3943 * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
3944 * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
3945 * this indicates we have a valid sample loaded for this effect.
3946 */
3947
3948 int numSamples = 0;
3949 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
3950 // Do not load sample if this effect uses the MediaPlayer
3951 if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
3952 continue;
3953 }
3954 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
3955 String filePath = Environment.getRootDirectory()
3956 + SOUND_EFFECTS_PATH
3957 + SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effect][0]);
3958 int sampleId = mSoundPool.load(filePath, 0);
3959 if (sampleId <= 0) {
3960 Log.w(TAG, "Soundpool could not load file: "+filePath);
3961 } else {
3962 SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
3963 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
3964 numSamples++;
3965 }
3966 } else {
3967 SOUND_EFFECT_FILES_MAP[effect][1] =
3968 poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
3969 }
3970 }
3971 // wait for all samples to be loaded
3972 if (numSamples > 0) {
3973 mSoundPoolCallBack.setSamples(poolId);
3974
3975 attempts = 3;
3976 status = 1;
3977 while ((status == 1) && (attempts-- > 0)) {
3978 try {
Glenn Kasten167d1a22013-07-23 16:24:41 -07003979 mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003980 status = mSoundPoolCallBack.status();
3981 } catch (InterruptedException e) {
3982 Log.w(TAG, "Interrupted while waiting sound pool callback.");
3983 }
3984 }
3985 } else {
3986 status = -1;
3987 }
3988
3989 if (mSoundPoolLooper != null) {
3990 mSoundPoolLooper.quit();
3991 mSoundPoolLooper = null;
3992 }
3993 mSoundPoolListenerThread = null;
3994 if (status != 0) {
3995 Log.w(TAG,
3996 "onLoadSoundEffects(), Error "+status+ " while loading samples");
3997 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
3998 if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) {
3999 SOUND_EFFECT_FILES_MAP[effect][1] = -1;
4000 }
4001 }
4002
4003 mSoundPool.release();
4004 mSoundPool = null;
4005 }
4006 }
4007 return (status == 0);
4008 }
4009
4010 /**
4011 * Unloads samples from the sound pool.
4012 * This method can be called to free some memory when
4013 * sound effects are disabled.
4014 */
4015 private void onUnloadSoundEffects() {
4016 synchronized (mSoundEffectsLock) {
4017 if (mSoundPool == null) {
4018 return;
4019 }
4020
4021 int[] poolId = new int[SOUND_EFFECT_FILES.size()];
4022 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.size(); fileIdx++) {
4023 poolId[fileIdx] = 0;
4024 }
4025
4026 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
4027 if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
4028 continue;
4029 }
4030 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
4031 mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
4032 SOUND_EFFECT_FILES_MAP[effect][1] = -1;
4033 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
4034 }
4035 }
4036 mSoundPool.release();
4037 mSoundPool = null;
4038 }
4039 }
4040
4041 private void onPlaySoundEffect(int effectType, int volume) {
4042 synchronized (mSoundEffectsLock) {
4043
4044 onLoadSoundEffects();
4045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 if (mSoundPool == null) {
4047 return;
4048 }
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004049 float volFloat;
Eric Laurent25101b02011-02-02 09:33:30 -08004050 // use default if volume is not specified by caller
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004051 if (volume < 0) {
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -07004052 volFloat = (float)Math.pow(10, (float)sSoundEffectVolumeDb/20);
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004053 } else {
RoboErik8a2cfc32014-05-16 11:19:38 -07004054 volFloat = volume / 1000.0f;
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056
4057 if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004058 mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1],
4059 volFloat, volFloat, 0, 0, 1.0f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 } else {
4061 MediaPlayer mediaPlayer = new MediaPlayer();
Glenn Kasten62b9aec2011-11-07 11:10:16 -08004062 try {
Eric Laurente78fced2013-03-15 16:03:47 -07004063 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH +
4064 SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effectType][0]);
Glenn Kasten62b9aec2011-11-07 11:10:16 -08004065 mediaPlayer.setDataSource(filePath);
4066 mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
4067 mediaPlayer.prepare();
Glenn Kasten068225d2012-02-27 16:21:04 -08004068 mediaPlayer.setVolume(volFloat);
Glenn Kasten62b9aec2011-11-07 11:10:16 -08004069 mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
4070 public void onCompletion(MediaPlayer mp) {
4071 cleanupPlayer(mp);
4072 }
4073 });
4074 mediaPlayer.setOnErrorListener(new OnErrorListener() {
4075 public boolean onError(MediaPlayer mp, int what, int extra) {
4076 cleanupPlayer(mp);
4077 return true;
4078 }
4079 });
4080 mediaPlayer.start();
4081 } catch (IOException ex) {
4082 Log.w(TAG, "MediaPlayer IOException: "+ex);
4083 } catch (IllegalArgumentException ex) {
4084 Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
4085 } catch (IllegalStateException ex) {
4086 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 }
4088 }
4089 }
4090 }
4091
4092 private void cleanupPlayer(MediaPlayer mp) {
4093 if (mp != null) {
4094 try {
4095 mp.stop();
4096 mp.release();
4097 } catch (IllegalStateException ex) {
4098 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
4099 }
4100 }
4101 }
4102
Eric Laurentfa640152011-03-12 15:59:51 -08004103 private void setForceUse(int usage, int config) {
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004104 synchronized (mConnectedDevices) {
4105 setForceUseInt_SyncDevices(usage, config);
4106 }
Eric Laurentfa640152011-03-12 15:59:51 -08004107 }
4108
Eric Laurent05274f32012-11-29 12:48:18 -08004109 private void onPersistSafeVolumeState(int state) {
4110 Settings.Global.putInt(mContentResolver,
4111 Settings.Global.AUDIO_SAFE_VOLUME_STATE,
4112 state);
4113 }
4114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 @Override
4116 public void handleMessage(Message msg) {
Eric Laurentafbb0472011-12-15 09:04:23 -08004117 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118
Eric Laurent9bc8358d2011-11-18 16:43:31 -08004119 case MSG_SET_DEVICE_VOLUME:
4120 setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);
4121 break;
4122
4123 case MSG_SET_ALL_VOLUMES:
4124 setAllVolumes((VolumeStreamState) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 break;
4126
4127 case MSG_PERSIST_VOLUME:
Eric Laurent42b041e2013-03-29 11:36:03 -07004128 persistVolume((VolumeStreamState) msg.obj, msg.arg1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 break;
4130
Mike Lockwood5c55a052011-12-15 17:21:44 -05004131 case MSG_PERSIST_MASTER_VOLUME:
Eric Laurent83a017b2013-03-19 18:15:31 -07004132 if (mUseFixedVolume) {
4133 return;
4134 }
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004135 Settings.System.putFloatForUser(mContentResolver,
4136 Settings.System.VOLUME_MASTER,
RoboErik8a2cfc32014-05-16 11:19:38 -07004137 msg.arg1 / (float)1000.0,
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004138 UserHandle.USER_CURRENT);
Mike Lockwood5c55a052011-12-15 17:21:44 -05004139 break;
4140
Justin Koh57978ed2012-04-03 17:37:58 -07004141 case MSG_PERSIST_MASTER_VOLUME_MUTE:
Eric Laurent83a017b2013-03-19 18:15:31 -07004142 if (mUseFixedVolume) {
4143 return;
4144 }
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004145 Settings.System.putIntForUser(mContentResolver,
4146 Settings.System.VOLUME_MASTER_MUTE,
4147 msg.arg1,
Julia Reynoldsb53453f2014-08-22 11:42:43 -04004148 msg.arg2);
Justin Koh57978ed2012-04-03 17:37:58 -07004149 break;
4150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 case MSG_PERSIST_RINGER_MODE:
Glenn Kastenba195eb2011-12-13 09:30:40 -08004152 // note that the value persisted is the current ringer mode, not the
4153 // value of ringer mode as of the time the request was made to persist
John Spurlock661f2cf2014-11-17 10:29:10 -05004154 persistRingerMode(getRingerModeInternal());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 break;
4156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 case MSG_MEDIA_SERVER_DIED:
Eric Laurenteb4b8a22014-07-21 13:10:07 -07004158 if (!mSystemReady ||
4159 (AudioSystem.checkAudioFlinger() != AudioSystem.AUDIO_STATUS_OK)) {
Eric Laurent89e74ba2009-09-30 18:26:36 -07004160 Log.e(TAG, "Media server died.");
Eric Laurentafbb0472011-12-15 09:04:23 -08004161 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0,
Eric Laurent89e74ba2009-09-30 18:26:36 -07004162 null, 500);
Eric Laurentdfb881f2013-07-18 14:41:39 -07004163 break;
Eric Laurent89e74ba2009-09-30 18:26:36 -07004164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 Log.e(TAG, "Media server started.");
Eric Laurentdfb881f2013-07-18 14:41:39 -07004166
Eric Laurent3c652ca2010-06-21 20:46:26 -07004167 // indicate to audio HAL that we start the reconfiguration phase after a media
4168 // server crash
Eric Laurentdfb881f2013-07-18 14:41:39 -07004169 // Note that we only execute this when the media server
Eric Laurent3c652ca2010-06-21 20:46:26 -07004170 // process restarts after a crash, not the first time it is started.
4171 AudioSystem.setParameters("restarting=true");
4172
Glenn Kastenfd116ad2013-07-12 17:10:39 -07004173 readAndSetLowRamDevice();
4174
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004175 // Restore device connection states
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004176 synchronized (mConnectedDevices) {
4177 Set set = mConnectedDevices.entrySet();
4178 Iterator i = set.iterator();
Eric Laurent9bc8358d2011-11-18 16:43:31 -08004179 while (i.hasNext()) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004180 Map.Entry device = (Map.Entry)i.next();
4181 AudioSystem.setDeviceConnectionState(
4182 ((Integer)device.getKey()).intValue(),
4183 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004184 (String)device.getValue(),
4185 "unknown-device");
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004186 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004187 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004188 // Restore call state
4189 AudioSystem.setPhoneState(mMode);
4190
Eric Laurentd5603c12009-08-06 08:49:39 -07004191 // Restore forced usage for communcations and record
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004192 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
Eric Laurentd5603c12009-08-06 08:49:39 -07004193 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
Eric Laurentdd45d012012-10-08 09:04:34 -07004194 AudioSystem.setForceUse(AudioSystem.FOR_SYSTEM, mCameraSoundForced ?
4195 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004196
Eric Laurenta553c252009-07-17 12:17:14 -07004197 // Restore stream volumes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 int numStreamTypes = AudioSystem.getNumStreamTypes();
4199 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004201 AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08004202
4203 streamState.applyAllVolumes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004205
4206 // Restore ringer mode
John Spurlock661f2cf2014-11-17 10:29:10 -05004207 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent3c652ca2010-06-21 20:46:26 -07004208
Mike Lockwood90631542012-01-06 11:20:37 -05004209 // Restore master volume
4210 restoreMasterVolume();
4211
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004212 // Reset device orientation (if monitored for this device)
Eric Laurentd640bd32012-09-28 18:01:48 -07004213 if (mMonitorOrientation) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004214 setOrientationForAudioSystem();
4215 }
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07004216 if (mMonitorRotation) {
4217 setRotationForAudioSystem();
4218 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004219
Eric Laurent78472112012-05-21 08:57:21 -07004220 synchronized (mBluetoothA2dpEnabledLock) {
4221 AudioSystem.setForceUse(AudioSystem.FOR_MEDIA,
4222 mBluetoothA2dpEnabled ?
4223 AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP);
4224 }
Eric Laurentbff5ca52012-11-02 16:48:26 -07004225
4226 synchronized (mSettingsLock) {
4227 AudioSystem.setForceUse(AudioSystem.FOR_DOCK,
4228 mDockAudioMediaEnabled ?
4229 AudioSystem.FORCE_ANALOG_DOCK : AudioSystem.FORCE_NONE);
4230 }
Eric Laurent212532b2014-07-21 15:43:18 -07004231 if (mHdmiManager != null) {
4232 synchronized (mHdmiManager) {
4233 if (mHdmiTvClient != null) {
4234 setHdmiSystemAudioSupported(mHdmiSystemAudioSupported);
4235 }
4236 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09004237 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08004238
4239 synchronized (mAudioPolicies) {
4240 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
4241 policy.connectMixes();
4242 }
4243 }
4244
Eric Laurent3c652ca2010-06-21 20:46:26 -07004245 // indicate the end of reconfiguration phase to audio HAL
4246 AudioSystem.setParameters("restarting=false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 break;
4248
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004249 case MSG_UNLOAD_SOUND_EFFECTS:
4250 onUnloadSoundEffects();
4251 break;
4252
Eric Laurent117b7bb2011-01-16 17:07:27 -08004253 case MSG_LOAD_SOUND_EFFECTS:
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004254 //FIXME: onLoadSoundEffects() should be executed in a separate thread as it
4255 // can take several dozens of milliseconds to complete
4256 boolean loaded = onLoadSoundEffects();
4257 if (msg.obj != null) {
4258 LoadSoundEffectReply reply = (LoadSoundEffectReply)msg.obj;
4259 synchronized (reply) {
4260 reply.mStatus = loaded ? 0 : -1;
4261 reply.notify();
4262 }
4263 }
Eric Laurent117b7bb2011-01-16 17:07:27 -08004264 break;
4265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 case MSG_PLAY_SOUND_EFFECT:
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004267 onPlaySoundEffect(msg.arg1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 break;
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004269
4270 case MSG_BTA2DP_DOCK_TIMEOUT:
4271 // msg.obj == address of BTA2DP device
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004272 synchronized (mConnectedDevices) {
4273 makeA2dpDeviceUnavailableNow( (String) msg.obj );
4274 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004275 break;
Eric Laurentfa640152011-03-12 15:59:51 -08004276
4277 case MSG_SET_FORCE_USE:
Eric Laurentc390bed2012-07-03 12:24:05 -07004278 case MSG_SET_FORCE_BT_A2DP_USE:
Eric Laurentfa640152011-03-12 15:59:51 -08004279 setForceUse(msg.arg1, msg.arg2);
4280 break;
Jean-Michel Trivid589fea2011-04-15 11:28:10 -07004281
Eric Laurentdc03c612011-04-01 10:59:41 -07004282 case MSG_BT_HEADSET_CNCT_FAILED:
4283 resetBluetoothSco();
4284 break;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004285
4286 case MSG_SET_WIRED_DEVICE_CONNECTION_STATE:
Paul McLean10804eb2015-01-28 11:16:35 -08004287 { WiredDeviceConnectionState connectState =
4288 (WiredDeviceConnectionState)msg.obj;
4289 onSetWiredDeviceConnectionState(connectState.mType, connectState.mState,
4290 connectState.mAddress, connectState.mName);
4291 mAudioEventWakeLock.release();
4292 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004293 break;
4294
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004295 case MSG_SET_A2DP_SRC_CONNECTION_STATE:
4296 onSetA2dpSourceConnectionState((BluetoothDevice)msg.obj, msg.arg1);
4297 mAudioEventWakeLock.release();
4298 break;
4299
4300 case MSG_SET_A2DP_SINK_CONNECTION_STATE:
4301 onSetA2dpSinkConnectionState((BluetoothDevice)msg.obj, msg.arg1);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004302 mAudioEventWakeLock.release();
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004303 break;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004304
4305 case MSG_REPORT_NEW_ROUTES: {
4306 int N = mRoutesObservers.beginBroadcast();
4307 if (N > 0) {
4308 AudioRoutesInfo routes;
4309 synchronized (mCurAudioRoutes) {
4310 routes = new AudioRoutesInfo(mCurAudioRoutes);
4311 }
4312 while (N > 0) {
4313 N--;
4314 IAudioRoutesObserver obs = mRoutesObservers.getBroadcastItem(N);
4315 try {
4316 obs.dispatchAudioRoutesChanged(routes);
4317 } catch (RemoteException e) {
4318 }
4319 }
4320 }
4321 mRoutesObservers.finishBroadcast();
4322 break;
4323 }
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07004324
Eric Laurentc34dcc12012-09-10 13:51:52 -07004325 case MSG_CHECK_MUSIC_ACTIVE:
4326 onCheckMusicActive();
4327 break;
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004328
4329 case MSG_BROADCAST_AUDIO_BECOMING_NOISY:
4330 onSendBecomingNoisyIntent();
4331 break;
Eric Laurentd640bd32012-09-28 18:01:48 -07004332
4333 case MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED:
4334 case MSG_CONFIGURE_SAFE_MEDIA_VOLUME:
4335 onConfigureSafeVolume((msg.what == MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED));
4336 break;
Eric Laurent05274f32012-11-29 12:48:18 -08004337 case MSG_PERSIST_SAFE_VOLUME_STATE:
4338 onPersistSafeVolumeState(msg.arg1);
4339 break;
Jean-Michel Trivia578c482012-12-28 11:19:49 -08004340
Eric Laurent2a57ca92013-03-07 17:29:27 -08004341 case MSG_BROADCAST_BT_CONNECTION_STATE:
4342 onBroadcastScoConnectionState(msg.arg1);
4343 break;
Eric Laurent4a5eeb92014-05-06 10:49:04 -07004344
4345 case MSG_SYSTEM_READY:
4346 onSystemReady();
4347 break;
John Spurlockaa5ee4d2014-07-25 13:05:12 -04004348
4349 case MSG_PERSIST_MUSIC_ACTIVE_MS:
4350 final int musicActiveMs = msg.arg1;
4351 Settings.Secure.putIntForUser(mContentResolver,
4352 Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, musicActiveMs,
4353 UserHandle.USER_CURRENT);
4354 break;
Julia Reynoldsb53453f2014-08-22 11:42:43 -04004355 case MSG_PERSIST_MICROPHONE_MUTE:
4356 Settings.System.putIntForUser(mContentResolver,
4357 Settings.System.MICROPHONE_MUTE,
4358 msg.arg1,
4359 msg.arg2);
4360 break;
RoboErik5452e252015-02-06 15:33:53 -08004361 case MSG_UNMUTE_STREAM:
4362 onUnmuteStream(msg.arg1, msg.arg2);
4363 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 }
4365 }
4366 }
4367
Jason Parekhb1096152009-03-24 17:48:25 -07004368 private class SettingsObserver extends ContentObserver {
Eric Laurenta553c252009-07-17 12:17:14 -07004369
Jason Parekhb1096152009-03-24 17:48:25 -07004370 SettingsObserver() {
4371 super(new Handler());
4372 mContentResolver.registerContentObserver(Settings.System.getUriFor(
4373 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
Eric Laurent7ee1e4f2012-10-26 18:11:21 -07004374 mContentResolver.registerContentObserver(Settings.Global.getUriFor(
4375 Settings.Global.DOCK_AUDIO_MEDIA_ENABLED), false, this);
Jason Parekhb1096152009-03-24 17:48:25 -07004376 }
4377
4378 @Override
4379 public void onChange(boolean selfChange) {
4380 super.onChange(selfChange);
Glenn Kastenba195eb2011-12-13 09:30:40 -08004381 // FIXME This synchronized is not necessary if mSettingsLock only protects mRingerMode.
4382 // However there appear to be some missing locks around mRingerModeMutedStreams
4383 // and mRingerModeAffectedStreams, so will leave this synchronized for now.
4384 // mRingerModeMutedStreams and mMuteAffectedStreams are safe (only accessed once).
Eric Laurenta553c252009-07-17 12:17:14 -07004385 synchronized (mSettingsLock) {
Eric Laurent24e0d9b2013-10-03 18:15:07 -07004386 if (updateRingerModeAffectedStreams()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004387 /*
4388 * Ensure all stream types that should be affected by ringer mode
4389 * are in the proper state.
4390 */
John Spurlock661f2cf2014-11-17 10:29:10 -05004391 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurenta553c252009-07-17 12:17:14 -07004392 }
Eric Laurent7ee1e4f2012-10-26 18:11:21 -07004393 readDockAudioSettings(mContentResolver);
Eric Laurenta553c252009-07-17 12:17:14 -07004394 }
Jason Parekhb1096152009-03-24 17:48:25 -07004395 }
Jason Parekhb1096152009-03-24 17:48:25 -07004396 }
Eric Laurenta553c252009-07-17 12:17:14 -07004397
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004398 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004399 private void makeA2dpDeviceAvailable(String address) {
Eric Laurent78472112012-05-21 08:57:21 -07004400 // enable A2DP before notifying A2DP connection to avoid unecessary processing in
4401 // audio policy manager
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004402 VolumeStreamState streamState = mStreamStates[AudioSystem.STREAM_MUSIC];
4403 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
4404 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0, streamState, 0);
Eric Laurent78472112012-05-21 08:57:21 -07004405 setBluetoothA2dpOnInt(true);
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004406 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
4407 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004408 address,
4409 "a2dp-device");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004410 // Reset A2DP suspend state each time a new sink is connected
4411 AudioSystem.setParameters("A2dpSuspended=false");
4412 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
4413 address);
4414 }
4415
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004416 private void onSendBecomingNoisyIntent() {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004417 sendBroadcastToAll(new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
Mike Lockwood98418182012-05-10 17:13:20 -07004418 }
4419
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004420 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004421 private void makeA2dpDeviceUnavailableNow(String address) {
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004422 synchronized (mA2dpAvrcpLock) {
4423 mAvrcpAbsVolSupported = false;
4424 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004425 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
4426 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004427 address,
4428 "a2dp-device");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004429 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
RoboErik5535ea82014-09-25 14:53:16 -07004430 synchronized (mCurAudioRoutes) {
4431 // Remove A2DP routes as well
John Spurlock61560172015-02-06 19:46:04 -05004432 if (mCurAudioRoutes.bluetoothName != null) {
4433 mCurAudioRoutes.bluetoothName = null;
RoboErik5535ea82014-09-25 14:53:16 -07004434 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4435 SENDMSG_NOOP, 0, 0, null, 0);
4436 }
4437 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004438 }
4439
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004440 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004441 private void makeA2dpDeviceUnavailableLater(String address) {
Eric Laurent3b591262010-04-20 07:01:00 -07004442 // prevent any activity on the A2DP audio output to avoid unwanted
4443 // reconnection of the sink.
4444 AudioSystem.setParameters("A2dpSuspended=true");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004445 // the device will be made unavailable later, so consider it disconnected right away
4446 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
4447 // send the delayed message to make the device unavailable later
4448 Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
4449 mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
4450
4451 }
4452
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004453 // must be called synchronized on mConnectedDevices
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004454 private void makeA2dpSrcAvailable(String address) {
4455 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
4456 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004457 address,
4458 "a2dp-device");
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004459 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP),
4460 address);
4461 }
4462
4463 // must be called synchronized on mConnectedDevices
4464 private void makeA2dpSrcUnavailable(String address) {
4465 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
4466 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004467 address,
4468 "a2dp-device");
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004469 mConnectedDevices.remove(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP);
4470 }
4471
4472 // must be called synchronized on mConnectedDevices
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004473 private void cancelA2dpDeviceTimeout() {
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004474 mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
4475 }
4476
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004477 // must be called synchronized on mConnectedDevices
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004478 private boolean hasScheduledA2dpDockTimeout() {
4479 return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
4480 }
4481
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004482 private void onSetA2dpSinkConnectionState(BluetoothDevice btDevice, int state)
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004483 {
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004484 if (DEBUG_VOL) {
4485 Log.d(TAG, "onSetA2dpSinkConnectionState btDevice="+btDevice+"state="+state);
4486 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004487 if (btDevice == null) {
4488 return;
4489 }
4490 String address = btDevice.getAddress();
4491 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4492 address = "";
4493 }
John Du5a0cf7a2013-07-19 11:30:34 -07004494
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004495 synchronized (mConnectedDevices) {
4496 boolean isConnected =
4497 (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
4498 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
4499
4500 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
4501 if (btDevice.isBluetoothDock()) {
4502 if (state == BluetoothProfile.STATE_DISCONNECTED) {
4503 // introduction of a delay for transient disconnections of docks when
4504 // power is rapidly turned off/on, this message will be canceled if
4505 // we reconnect the dock under a preset delay
4506 makeA2dpDeviceUnavailableLater(address);
4507 // the next time isConnected is evaluated, it will be false for the dock
4508 }
4509 } else {
4510 makeA2dpDeviceUnavailableNow(address);
4511 }
Dianne Hackborn632ca412012-06-14 19:34:10 -07004512 synchronized (mCurAudioRoutes) {
John Spurlock61560172015-02-06 19:46:04 -05004513 if (mCurAudioRoutes.bluetoothName != null) {
4514 mCurAudioRoutes.bluetoothName = null;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004515 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4516 SENDMSG_NOOP, 0, 0, null, 0);
4517 }
4518 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004519 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
4520 if (btDevice.isBluetoothDock()) {
4521 // this could be a reconnection after a transient disconnection
4522 cancelA2dpDeviceTimeout();
4523 mDockAddress = address;
4524 } else {
4525 // this could be a connection of another A2DP device before the timeout of
4526 // a dock: cancel the dock timeout, and make the dock unavailable now
4527 if(hasScheduledA2dpDockTimeout()) {
4528 cancelA2dpDeviceTimeout();
4529 makeA2dpDeviceUnavailableNow(mDockAddress);
4530 }
4531 }
4532 makeA2dpDeviceAvailable(address);
Dianne Hackborn632ca412012-06-14 19:34:10 -07004533 synchronized (mCurAudioRoutes) {
4534 String name = btDevice.getAliasName();
John Spurlock61560172015-02-06 19:46:04 -05004535 if (!TextUtils.equals(mCurAudioRoutes.bluetoothName, name)) {
4536 mCurAudioRoutes.bluetoothName = name;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004537 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4538 SENDMSG_NOOP, 0, 0, null, 0);
4539 }
4540 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004541 }
4542 }
4543 }
4544
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004545 private void onSetA2dpSourceConnectionState(BluetoothDevice btDevice, int state)
4546 {
4547 if (DEBUG_VOL) {
4548 Log.d(TAG, "onSetA2dpSourceConnectionState btDevice="+btDevice+" state="+state);
4549 }
4550 if (btDevice == null) {
4551 return;
4552 }
4553 String address = btDevice.getAddress();
4554 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4555 address = "";
4556 }
4557
4558 synchronized (mConnectedDevices) {
4559 boolean isConnected =
4560 (mConnectedDevices.containsKey(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP) &&
4561 mConnectedDevices.get(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP).equals(address));
4562
4563 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
4564 makeA2dpSrcUnavailable(address);
4565 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
4566 makeA2dpSrcAvailable(address);
4567 }
4568 }
4569 }
4570
John Du5a0cf7a2013-07-19 11:30:34 -07004571 public void avrcpSupportsAbsoluteVolume(String address, boolean support) {
4572 // address is not used for now, but may be used when multiple a2dp devices are supported
4573 synchronized (mA2dpAvrcpLock) {
4574 mAvrcpAbsVolSupported = support;
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004575 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
Eric Laurentcd772d02013-10-30 18:31:07 -07004576 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0,
4577 mStreamStates[AudioSystem.STREAM_MUSIC], 0);
4578 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
4579 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0,
4580 mStreamStates[AudioSystem.STREAM_RING], 0);
John Du5a0cf7a2013-07-19 11:30:34 -07004581 }
4582 }
4583
Paul McLean10804eb2015-01-28 11:16:35 -08004584 private boolean handleDeviceConnection(boolean connect, int device, String address, String deviceName) {
4585 Slog.i(TAG, "handleDeviceConnection(" + connect +
4586 " dev:" + Integer.toHexString(device) +
RoboErik5452e252015-02-06 15:33:53 -08004587 " address:" + address +
Paul McLean10804eb2015-01-28 11:16:35 -08004588 " name:" + deviceName + ")");
Eric Laurent59f48272012-04-05 19:42:21 -07004589 synchronized (mConnectedDevices) {
4590 boolean isConnected = (mConnectedDevices.containsKey(device) &&
Paul McLean10804eb2015-01-28 11:16:35 -08004591 (address.isEmpty() || mConnectedDevices.get(device).equals(address)));
Eric Laurent59f48272012-04-05 19:42:21 -07004592
Paul McLean10804eb2015-01-28 11:16:35 -08004593 if (isConnected && !connect) {
Eric Laurent59f48272012-04-05 19:42:21 -07004594 AudioSystem.setDeviceConnectionState(device,
4595 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004596 address, deviceName);
Eric Laurent59f48272012-04-05 19:42:21 -07004597 mConnectedDevices.remove(device);
4598 return true;
Paul McLean10804eb2015-01-28 11:16:35 -08004599 } else if (!isConnected && connect) {
Eric Laurent59f48272012-04-05 19:42:21 -07004600 AudioSystem.setDeviceConnectionState(device,
4601 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004602 address, deviceName);
4603 mConnectedDevices.put(new Integer(device), address);
Eric Laurent59f48272012-04-05 19:42:21 -07004604 return true;
4605 }
4606 }
4607 return false;
4608 }
4609
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004610 // Devices which removal triggers intent ACTION_AUDIO_BECOMING_NOISY. The intent is only
4611 // sent if none of these devices is connected.
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004612 // Access synchronized on mConnectedDevices
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004613 int mBecomingNoisyIntentDevices =
4614 AudioSystem.DEVICE_OUT_WIRED_HEADSET | AudioSystem.DEVICE_OUT_WIRED_HEADPHONE |
Eric Laurent948d3272014-05-16 15:18:45 -07004615 AudioSystem.DEVICE_OUT_ALL_A2DP | AudioSystem.DEVICE_OUT_HDMI |
Eric Laurent794da7a2012-08-30 11:30:16 -07004616 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET | AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET |
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004617 AudioSystem.DEVICE_OUT_ALL_USB | AudioSystem.DEVICE_OUT_LINE;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004618
4619 // must be called before removing the device from mConnectedDevices
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004620 // Called synchronized on mConnectedDevices
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004621 private int checkSendBecomingNoisyIntent(int device, int state) {
4622 int delay = 0;
4623 if ((state == 0) && ((device & mBecomingNoisyIntentDevices) != 0)) {
4624 int devices = 0;
4625 for (int dev : mConnectedDevices.keySet()) {
Eric Laurent27c30e42014-08-27 12:36:33 -07004626 if (((dev & AudioSystem.DEVICE_BIT_IN) == 0) &&
4627 ((dev & mBecomingNoisyIntentDevices) != 0)) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004628 devices |= dev;
4629 }
4630 }
4631 if (devices == device) {
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004632 sendMsg(mAudioHandler,
4633 MSG_BROADCAST_AUDIO_BECOMING_NOISY,
4634 SENDMSG_REPLACE,
4635 0,
4636 0,
4637 null,
4638 0);
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004639 delay = 1000;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004640 }
4641 }
4642
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004643 if (mAudioHandler.hasMessages(MSG_SET_A2DP_SRC_CONNECTION_STATE) ||
4644 mAudioHandler.hasMessages(MSG_SET_A2DP_SINK_CONNECTION_STATE) ||
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004645 mAudioHandler.hasMessages(MSG_SET_WIRED_DEVICE_CONNECTION_STATE)) {
Eric Laurentadbe8bf2014-11-03 18:26:32 -08004646 synchronized (mLastDeviceConnectMsgTime) {
4647 long time = SystemClock.uptimeMillis();
4648 if (mLastDeviceConnectMsgTime > time) {
Matthew Xiec525cf72015-01-22 20:13:17 -08004649 delay = (int)(mLastDeviceConnectMsgTime - time) + 30;
Eric Laurentadbe8bf2014-11-03 18:26:32 -08004650 }
4651 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004652 }
4653 return delay;
4654 }
4655
Paul McLean10804eb2015-01-28 11:16:35 -08004656 private void sendDeviceConnectionIntent(int device, int state, String address, String deviceName)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004657 {
Paul McLean10804eb2015-01-28 11:16:35 -08004658 Slog.i(TAG, "sendDeviceConnectionIntent(dev:0x" + Integer.toHexString(device) +
4659 " state:0x" + Integer.toHexString(state) +
4660 " address:" + address +
4661 " name:" + deviceName + ");");
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004662 Intent intent = new Intent();
4663
Paul McLean10804eb2015-01-28 11:16:35 -08004664 intent.putExtra(CONNECT_INTENT_KEY_STATE, state);
4665 intent.putExtra(CONNECT_INTENT_KEY_ADDRESS, address);
4666 intent.putExtra(CONNECT_INTENT_KEY_PORT_NAME, deviceName);
4667
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004668 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4669
Dianne Hackborn632ca412012-06-14 19:34:10 -07004670 int connType = 0;
4671
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004672 if (device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) {
Dianne Hackborn632ca412012-06-14 19:34:10 -07004673 connType = AudioRoutesInfo.MAIN_HEADSET;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004674 intent.setAction(Intent.ACTION_HEADSET_PLUG);
4675 intent.putExtra("microphone", 1);
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004676 } else if (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE ||
4677 device == AudioSystem.DEVICE_OUT_LINE) {
4678 /*do apps care about line-out vs headphones?*/
Dianne Hackborn632ca412012-06-14 19:34:10 -07004679 connType = AudioRoutesInfo.MAIN_HEADPHONES;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004680 intent.setAction(Intent.ACTION_HEADSET_PLUG);
4681 intent.putExtra("microphone", 0);
Eric Laurent6fa42452015-01-09 15:09:40 -08004682 } else if (device == AudioSystem.DEVICE_OUT_HDMI ||
4683 device == AudioSystem.DEVICE_OUT_HDMI_ARC) {
Dianne Hackborn632ca412012-06-14 19:34:10 -07004684 connType = AudioRoutesInfo.MAIN_HDMI;
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004685 configureHdmiPlugIntent(intent, state);
Paul McLean10804eb2015-01-28 11:16:35 -08004686 } else if (device == AudioSystem.DEVICE_OUT_USB_DEVICE) {
4687 connType = AudioRoutesInfo.MAIN_USB;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004688 }
4689
Dianne Hackborn632ca412012-06-14 19:34:10 -07004690 synchronized (mCurAudioRoutes) {
4691 if (connType != 0) {
John Spurlock61560172015-02-06 19:46:04 -05004692 int newConn = mCurAudioRoutes.mainType;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004693 if (state != 0) {
4694 newConn |= connType;
4695 } else {
4696 newConn &= ~connType;
4697 }
John Spurlock61560172015-02-06 19:46:04 -05004698 if (newConn != mCurAudioRoutes.mainType) {
4699 mCurAudioRoutes.mainType = newConn;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004700 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4701 SENDMSG_NOOP, 0, 0, null, 0);
4702 }
4703 }
4704 }
4705
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004706 final long ident = Binder.clearCallingIdentity();
4707 try {
4708 ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
4709 } finally {
4710 Binder.restoreCallingIdentity(ident);
4711 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004712 }
4713
Paul McLean10804eb2015-01-28 11:16:35 -08004714 private void onSetWiredDeviceConnectionState(int device, int state, String address,
4715 String deviceName)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004716 {
Paul McLean10804eb2015-01-28 11:16:35 -08004717 Slog.i(TAG, "onSetWiredDeviceConnectionState(dev:" + Integer.toHexString(device)
4718 + " state:" + Integer.toHexString(state)
4719 + " address:" + address
4720 + " deviceName:" + deviceName + ");");
4721
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004722 synchronized (mConnectedDevices) {
4723 if ((state == 0) && ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004724 (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) ||
4725 (device == AudioSystem.DEVICE_OUT_LINE))) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004726 setBluetoothA2dpOnInt(true);
4727 }
Eric Laurentae4506e2014-05-29 16:04:32 -07004728 boolean isUsb = ((device & ~AudioSystem.DEVICE_OUT_ALL_USB) == 0) ||
4729 (((device & AudioSystem.DEVICE_BIT_IN) != 0) &&
4730 ((device & ~AudioSystem.DEVICE_IN_ALL_USB) == 0));
Paul McLean10804eb2015-01-28 11:16:35 -08004731 handleDeviceConnection(state == 1, device, address, deviceName);
Eric Laurentf1a457d2012-09-20 16:27:23 -07004732 if (state != 0) {
4733 if ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004734 (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) ||
4735 (device == AudioSystem.DEVICE_OUT_LINE)) {
Eric Laurentf1a457d2012-09-20 16:27:23 -07004736 setBluetoothA2dpOnInt(false);
4737 }
4738 if ((device & mSafeMediaVolumeDevices) != 0) {
4739 sendMsg(mAudioHandler,
4740 MSG_CHECK_MUSIC_ACTIVE,
4741 SENDMSG_REPLACE,
4742 0,
4743 0,
4744 null,
4745 MUSIC_ACTIVE_POLL_PERIOD_MS);
4746 }
Eric Laurent212532b2014-07-21 15:43:18 -07004747 // Television devices without CEC service apply software volume on HDMI output
4748 if (isPlatformTelevision() && ((device & AudioSystem.DEVICE_OUT_HDMI) != 0)) {
4749 mFixedVolumeDevices |= AudioSystem.DEVICE_OUT_HDMI;
4750 checkAllFixedVolumeDevices();
4751 if (mHdmiManager != null) {
4752 synchronized (mHdmiManager) {
4753 if (mHdmiPlaybackClient != null) {
4754 mHdmiCecSink = false;
4755 mHdmiPlaybackClient.queryDisplayStatus(mHdmiDisplayStatusCallback);
4756 }
4757 }
4758 }
4759 }
4760 } else {
4761 if (isPlatformTelevision() && ((device & AudioSystem.DEVICE_OUT_HDMI) != 0)) {
4762 if (mHdmiManager != null) {
4763 synchronized (mHdmiManager) {
4764 mHdmiCecSink = false;
4765 }
4766 }
4767 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004768 }
Paul McLean10804eb2015-01-28 11:16:35 -08004769 if (!isUsb && device != AudioSystem.DEVICE_IN_WIRED_HEADSET) {
4770 sendDeviceConnectionIntent(device, state, address, deviceName);
Mike Lockwooddb454842012-09-18 11:16:57 -07004771 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004772 }
4773 }
4774
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004775 private void configureHdmiPlugIntent(Intent intent, int state) {
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004776 intent.setAction(AudioManager.ACTION_HDMI_AUDIO_PLUG);
4777 intent.putExtra(AudioManager.EXTRA_AUDIO_PLUG_STATE, state);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004778 if (state == 1) {
4779 ArrayList<AudioPort> ports = new ArrayList<AudioPort>();
4780 int[] portGeneration = new int[1];
4781 int status = AudioSystem.listAudioPorts(ports, portGeneration);
4782 if (status == AudioManager.SUCCESS) {
4783 for (AudioPort port : ports) {
4784 if (port instanceof AudioDevicePort) {
4785 final AudioDevicePort devicePort = (AudioDevicePort) port;
Eric Laurent6fa42452015-01-09 15:09:40 -08004786 if (devicePort.type() == AudioManager.DEVICE_OUT_HDMI ||
4787 devicePort.type() == AudioManager.DEVICE_OUT_HDMI_ARC) {
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004788 // format the list of supported encodings
4789 int[] formats = devicePort.formats();
4790 if (formats.length > 0) {
4791 ArrayList<Integer> encodingList = new ArrayList(1);
4792 for (int format : formats) {
4793 // a format in the list can be 0, skip it
4794 if (format != AudioFormat.ENCODING_INVALID) {
4795 encodingList.add(format);
4796 }
4797 }
4798 int[] encodingArray = new int[encodingList.size()];
4799 for (int i = 0 ; i < encodingArray.length ; i++) {
4800 encodingArray[i] = encodingList.get(i);
4801 }
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004802 intent.putExtra(AudioManager.EXTRA_ENCODINGS, encodingArray);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004803 }
4804 // find the maximum supported number of channels
4805 int maxChannels = 0;
4806 for (int mask : devicePort.channelMasks()) {
4807 int channelCount = AudioFormat.channelCountFromOutChannelMask(mask);
4808 if (channelCount > maxChannels) {
4809 maxChannels = channelCount;
4810 }
4811 }
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004812 intent.putExtra(AudioManager.EXTRA_MAX_CHANNEL_COUNT, maxChannels);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004813 }
4814 }
4815 }
4816 }
4817 }
4818 }
4819
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004820 /* cache of the address of the last dock the device was connected to */
4821 private String mDockAddress;
4822
Eric Laurenta553c252009-07-17 12:17:14 -07004823 /**
4824 * Receiver for misc intent broadcasts the Phone app cares about.
4825 */
4826 private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
4827 @Override
4828 public void onReceive(Context context, Intent intent) {
4829 String action = intent.getAction();
Eric Laurentae4506e2014-05-29 16:04:32 -07004830 int outDevice;
4831 int inDevice;
Eric Laurent59f48272012-04-05 19:42:21 -07004832 int state;
Eric Laurenta553c252009-07-17 12:17:14 -07004833
Jean-Michel Trivi758559e2010-03-09 09:26:08 -08004834 if (action.equals(Intent.ACTION_DOCK_EVENT)) {
4835 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4836 Intent.EXTRA_DOCK_STATE_UNDOCKED);
4837 int config;
4838 switch (dockState) {
4839 case Intent.EXTRA_DOCK_STATE_DESK:
4840 config = AudioSystem.FORCE_BT_DESK_DOCK;
4841 break;
4842 case Intent.EXTRA_DOCK_STATE_CAR:
4843 config = AudioSystem.FORCE_BT_CAR_DOCK;
4844 break;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05004845 case Intent.EXTRA_DOCK_STATE_LE_DESK:
Eric Laurent08ed1b92012-11-05 14:54:12 -08004846 config = AudioSystem.FORCE_ANALOG_DOCK;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05004847 break;
4848 case Intent.EXTRA_DOCK_STATE_HE_DESK:
4849 config = AudioSystem.FORCE_DIGITAL_DOCK;
4850 break;
Jean-Michel Trivi758559e2010-03-09 09:26:08 -08004851 case Intent.EXTRA_DOCK_STATE_UNDOCKED:
4852 default:
4853 config = AudioSystem.FORCE_NONE;
4854 }
Eric Laurent08ed1b92012-11-05 14:54:12 -08004855 // Low end docks have a menu to enable or disable audio
4856 // (see mDockAudioMediaEnabled)
4857 if (!((dockState == Intent.EXTRA_DOCK_STATE_LE_DESK) ||
4858 ((dockState == Intent.EXTRA_DOCK_STATE_UNDOCKED) &&
4859 (mDockState == Intent.EXTRA_DOCK_STATE_LE_DESK)))) {
4860 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
4861 }
4862 mDockState = dockState;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07004863 } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
Eric Laurent59f48272012-04-05 19:42:21 -07004864 state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07004865 BluetoothProfile.STATE_DISCONNECTED);
Eric Laurentae4506e2014-05-29 16:04:32 -07004866 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
4867 inDevice = AudioSystem.DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Nick Pellya56d1c72009-08-19 14:49:29 -07004868 String address = null;
Eric Laurentdca56b92011-09-02 14:20:56 -07004869
4870 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
4871 if (btDevice == null) {
4872 return;
4873 }
4874
4875 address = btDevice.getAddress();
4876 BluetoothClass btClass = btDevice.getBluetoothClass();
4877 if (btClass != null) {
4878 switch (btClass.getDeviceClass()) {
4879 case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
4880 case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
Eric Laurentae4506e2014-05-29 16:04:32 -07004881 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurentdca56b92011-09-02 14:20:56 -07004882 break;
4883 case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
Eric Laurentae4506e2014-05-29 16:04:32 -07004884 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurentdca56b92011-09-02 14:20:56 -07004885 break;
Eric Laurentd5603c12009-08-06 08:49:39 -07004886 }
4887 }
4888
Eric Laurentdca56b92011-09-02 14:20:56 -07004889 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4890 address = "";
4891 }
Eric Laurentd5603c12009-08-06 08:49:39 -07004892
Eric Laurent59f48272012-04-05 19:42:21 -07004893 boolean connected = (state == BluetoothProfile.STATE_CONNECTED);
Paul McLean10804eb2015-01-28 11:16:35 -08004894 boolean success =
4895 handleDeviceConnection(connected, outDevice, address, "Bluetooth Headset") &&
4896 handleDeviceConnection(connected, inDevice, address, "Bluetooth Headset");
Eric Laurentae4506e2014-05-29 16:04:32 -07004897 if (success) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004898 synchronized (mScoClients) {
Eric Laurent59f48272012-04-05 19:42:21 -07004899 if (connected) {
4900 mBluetoothHeadsetDevice = btDevice;
4901 } else {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004902 mBluetoothHeadsetDevice = null;
4903 resetBluetoothSco();
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004904 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004905 }
Eric Laurenta553c252009-07-17 12:17:14 -07004906 }
Paul McLeandf361462014-04-10 16:02:55 -07004907 } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004908 boolean broadcast = false;
Eric Laurent59f48272012-04-05 19:42:21 -07004909 int scoAudioState = AudioManager.SCO_AUDIO_STATE_ERROR;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004910 synchronized (mScoClients) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004911 int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
Eric Laurentdc03c612011-04-01 10:59:41 -07004912 // broadcast intent if the connection was initated by AudioService
4913 if (!mScoClients.isEmpty() &&
4914 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
4915 mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
4916 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004917 broadcast = true;
4918 }
4919 switch (btState) {
4920 case BluetoothHeadset.STATE_AUDIO_CONNECTED:
Eric Laurent59f48272012-04-05 19:42:21 -07004921 scoAudioState = AudioManager.SCO_AUDIO_STATE_CONNECTED;
Eric Laurentdc03c612011-04-01 10:59:41 -07004922 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
4923 mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
4924 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004925 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004926 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004927 break;
4928 case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
Eric Laurent59f48272012-04-05 19:42:21 -07004929 scoAudioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
Eric Laurent62ef7672010-11-24 10:58:32 -08004930 mScoAudioState = SCO_STATE_INACTIVE;
Eric Laurentd7454be2011-09-14 08:45:58 -07004931 clearAllScoClients(0, false);
Eric Laurent62ef7672010-11-24 10:58:32 -08004932 break;
4933 case BluetoothHeadset.STATE_AUDIO_CONNECTING:
Eric Laurentdc03c612011-04-01 10:59:41 -07004934 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
4935 mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
4936 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004937 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004938 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004939 default:
4940 // do not broadcast CONNECTING or invalid state
4941 broadcast = false;
4942 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004943 }
4944 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004945 if (broadcast) {
Eric Laurent59f48272012-04-05 19:42:21 -07004946 broadcastScoConnectionState(scoAudioState);
Eric Laurentdc03c612011-04-01 10:59:41 -07004947 //FIXME: this is to maintain compatibility with deprecated intent
4948 // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Eric Laurent62ef7672010-11-24 10:58:32 -08004949 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
Eric Laurent59f48272012-04-05 19:42:21 -07004950 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, scoAudioState);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004951 sendStickyBroadcastToAll(newIntent);
Eric Laurent62ef7672010-11-24 10:58:32 -08004952 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004953 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
Jon Eklund318f0fe2014-01-23 17:53:48 -06004954 if (mMonitorRotation) {
4955 mOrientationListener.onOrientationChanged(0); //argument is ignored anyway
4956 mOrientationListener.enable();
4957 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004958 AudioSystem.setParameters("screen_state=on");
4959 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Jon Eklund318f0fe2014-01-23 17:53:48 -06004960 if (mMonitorRotation) {
4961 //reduce wakeups (save current) by only listening when display is on
4962 mOrientationListener.disable();
4963 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004964 AudioSystem.setParameters("screen_state=off");
Dianne Hackborn961cae92013-03-20 14:59:43 -07004965 } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004966 handleConfigurationChanged(context);
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004967 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004968 // attempt to stop music playback for background user
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004969 sendMsg(mAudioHandler,
4970 MSG_BROADCAST_AUDIO_BECOMING_NOISY,
4971 SENDMSG_REPLACE,
4972 0,
4973 0,
4974 null,
4975 0);
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004976 // the current audio focus owner is no longer valid
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004977 mMediaFocusControl.discardAudioFocusOwner();
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004978
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004979 // load volume settings for new user
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004980 readAudioSettings(true /*userSwitch*/);
4981 // preserve STREAM_MUSIC volume from one user to the next.
4982 sendMsg(mAudioHandler,
4983 MSG_SET_ALL_VOLUMES,
4984 SENDMSG_QUEUE,
4985 0,
4986 0,
4987 mStreamStates[AudioSystem.STREAM_MUSIC], 0);
Eric Laurenta553c252009-07-17 12:17:14 -07004988 }
4989 }
Paul McLeanc837a452014-04-09 09:04:43 -07004990 } // end class AudioServiceBroadcastReceiver
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08004991
4992 //==========================================================================================
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004993 // RemoteControlDisplay / RemoteControlClient / Remote info
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08004994 //==========================================================================================
Jean-Michel Trivif108cdd92013-09-27 18:37:36 -07004995 public boolean registerRemoteController(IRemoteControlDisplay rcd, int w, int h,
4996 ComponentName listenerComp) {
4997 return mMediaFocusControl.registerRemoteController(rcd, w, h, listenerComp);
4998 }
4999
Jean-Michel Trivi7ddd2262013-09-01 18:06:45 -07005000 public boolean registerRemoteControlDisplay(IRemoteControlDisplay rcd, int w, int h) {
Jean-Michel Trivif108cdd92013-09-27 18:37:36 -07005001 return mMediaFocusControl.registerRemoteControlDisplay(rcd, w, h);
Jean-Michel Trivi8f619182011-07-21 15:10:10 -07005002 }
Jean-Michel Trivid327f212010-03-16 21:44:33 -07005003
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07005004 public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005005 mMediaFocusControl.unregisterRemoteControlDisplay(rcd);
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07005006 }
5007
5008 public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005009 mMediaFocusControl.remoteControlDisplayUsesBitmapSize(rcd, w, h);
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07005010 }
5011
Jean-Michel Trivic3c4bab2013-04-19 08:56:50 -07005012 public void remoteControlDisplayWantsPlaybackPositionSync(IRemoteControlDisplay rcd,
5013 boolean wantsSync) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005014 mMediaFocusControl.remoteControlDisplayWantsPlaybackPositionSync(rcd, wantsSync);
5015 }
5016
John Spurlock3346a802014-05-20 16:25:37 -04005017 @Override
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005018 public void setRemoteStreamVolume(int index) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005019 enforceVolumeController("set the remote stream volume");
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005020 mMediaFocusControl.setRemoteStreamVolume(index);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07005021 }
5022
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005023 //==========================================================================================
5024 // Audio Focus
5025 //==========================================================================================
Jean-Michel Trivifd6ad742014-11-10 14:38:30 -08005026 public int requestAudioFocus(AudioAttributes aa, int durationHint, IBinder cb,
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005027 IAudioFocusDispatcher fd, String clientId, String callingPackageName, int flags,
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005028 IAudioPolicyCallback pcb) {
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005029 // permission checks
5030 if ((flags & AudioManager.AUDIOFOCUS_FLAG_LOCK) == AudioManager.AUDIOFOCUS_FLAG_LOCK) {
John Spurlock61560172015-02-06 19:46:04 -05005031 if (AudioSystem.IN_VOICE_COMM_FOCUS_ID.equals(clientId)) {
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005032 if (PackageManager.PERMISSION_GRANTED != mContext.checkCallingOrSelfPermission(
5033 android.Manifest.permission.MODIFY_PHONE_STATE)) {
5034 Log.e(TAG, "Invalid permission to (un)lock audio focus", new Exception());
5035 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
5036 }
5037 } else {
5038 // only a registered audio policy can be used to lock focus
5039 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005040 if (!mAudioPolicies.containsKey(pcb.asBinder())) {
5041 Log.e(TAG, "Invalid unregistered AudioPolicy to (un)lock audio focus");
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005042 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
5043 }
5044 }
5045 }
5046 }
5047
Jean-Michel Trivifd6ad742014-11-10 14:38:30 -08005048 return mMediaFocusControl.requestAudioFocus(aa, durationHint, cb, fd,
5049 clientId, callingPackageName, flags);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005050 }
5051
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005052 public int abandonAudioFocus(IAudioFocusDispatcher fd, String clientId, AudioAttributes aa) {
5053 return mMediaFocusControl.abandonAudioFocus(fd, clientId, aa);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005054 }
5055
5056 public void unregisterAudioFocusClient(String clientId) {
5057 mMediaFocusControl.unregisterAudioFocusClient(clientId);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07005058 }
5059
Jean-Michel Trivi23805662013-07-31 14:19:18 -07005060 public int getCurrentAudioFocus() {
5061 return mMediaFocusControl.getCurrentAudioFocus();
5062 }
5063
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005064 //==========================================================================================
5065 // Device orientation
5066 //==========================================================================================
5067 /**
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005068 * Handles device configuration changes that may map to a change in the orientation
5069 * or orientation.
5070 * Monitoring orientation and rotation is optional, and is defined by the definition and value
5071 * of the "ro.audio.monitorOrientation" and "ro.audio.monitorRotation" system properties.
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005072 */
5073 private void handleConfigurationChanged(Context context) {
5074 try {
5075 // reading new orientation "safely" (i.e. under try catch) in case anything
5076 // goes wrong when obtaining resources and configuration
Eric Laurentd640bd32012-09-28 18:01:48 -07005077 Configuration config = context.getResources().getConfiguration();
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005078 // TODO merge rotation and orientation
Eric Laurentd640bd32012-09-28 18:01:48 -07005079 if (mMonitorOrientation) {
5080 int newOrientation = config.orientation;
5081 if (newOrientation != mDeviceOrientation) {
5082 mDeviceOrientation = newOrientation;
5083 setOrientationForAudioSystem();
5084 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005085 }
Eric Laurentd640bd32012-09-28 18:01:48 -07005086 sendMsg(mAudioHandler,
5087 MSG_CONFIGURE_SAFE_MEDIA_VOLUME,
5088 SENDMSG_REPLACE,
5089 0,
5090 0,
5091 null,
5092 0);
Eric Laurentdd45d012012-10-08 09:04:34 -07005093
5094 boolean cameraSoundForced = mContext.getResources().getBoolean(
5095 com.android.internal.R.bool.config_camera_sound_forced);
5096 synchronized (mSettingsLock) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005097 boolean cameraSoundForcedChanged = false;
Eric Laurentdd45d012012-10-08 09:04:34 -07005098 synchronized (mCameraSoundForced) {
5099 if (cameraSoundForced != mCameraSoundForced) {
5100 mCameraSoundForced = cameraSoundForced;
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005101 cameraSoundForcedChanged = true;
Eric Laurentdd45d012012-10-08 09:04:34 -07005102 }
5103 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005104 if (cameraSoundForcedChanged) {
5105 if (!isPlatformTelevision()) {
5106 VolumeStreamState s = mStreamStates[AudioSystem.STREAM_SYSTEM_ENFORCED];
5107 if (cameraSoundForced) {
5108 s.setAllIndexesToMax();
5109 mRingerModeAffectedStreams &=
5110 ~(1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
5111 } else {
5112 s.setAllIndexes(mStreamStates[AudioSystem.STREAM_SYSTEM]);
5113 mRingerModeAffectedStreams |=
5114 (1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
5115 }
5116 // take new state into account for streams muted by ringer mode
John Spurlock661f2cf2014-11-17 10:29:10 -05005117 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005118 }
5119
5120 sendMsg(mAudioHandler,
5121 MSG_SET_FORCE_USE,
5122 SENDMSG_QUEUE,
5123 AudioSystem.FOR_SYSTEM,
5124 cameraSoundForced ?
5125 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE,
5126 null,
5127 0);
5128
5129 sendMsg(mAudioHandler,
5130 MSG_SET_ALL_VOLUMES,
5131 SENDMSG_QUEUE,
5132 0,
5133 0,
5134 mStreamStates[AudioSystem.STREAM_SYSTEM_ENFORCED], 0);
5135 }
Eric Laurentdd45d012012-10-08 09:04:34 -07005136 }
John Spurlock3346a802014-05-20 16:25:37 -04005137 mVolumeController.setLayoutDirection(config.getLayoutDirection());
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005138 } catch (Exception e) {
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005139 Log.e(TAG, "Error handling configuration change: ", e);
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005140 }
5141 }
5142
5143 private void setOrientationForAudioSystem() {
5144 switch (mDeviceOrientation) {
5145 case Configuration.ORIENTATION_LANDSCAPE:
5146 //Log.i(TAG, "orientation is landscape");
5147 AudioSystem.setParameters("orientation=landscape");
5148 break;
5149 case Configuration.ORIENTATION_PORTRAIT:
5150 //Log.i(TAG, "orientation is portrait");
5151 AudioSystem.setParameters("orientation=portrait");
5152 break;
5153 case Configuration.ORIENTATION_SQUARE:
5154 //Log.i(TAG, "orientation is square");
5155 AudioSystem.setParameters("orientation=square");
5156 break;
5157 case Configuration.ORIENTATION_UNDEFINED:
5158 //Log.i(TAG, "orientation is undefined");
5159 AudioSystem.setParameters("orientation=undefined");
5160 break;
5161 default:
5162 Log.e(TAG, "Unknown orientation");
5163 }
5164 }
5165
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005166 private void setRotationForAudioSystem() {
5167 switch (mDeviceRotation) {
5168 case Surface.ROTATION_0:
5169 AudioSystem.setParameters("rotation=0");
5170 break;
5171 case Surface.ROTATION_90:
5172 AudioSystem.setParameters("rotation=90");
5173 break;
5174 case Surface.ROTATION_180:
5175 AudioSystem.setParameters("rotation=180");
5176 break;
5177 case Surface.ROTATION_270:
5178 AudioSystem.setParameters("rotation=270");
5179 break;
5180 default:
5181 Log.e(TAG, "Unknown device rotation");
5182 }
5183 }
5184
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005185
Eric Laurent78472112012-05-21 08:57:21 -07005186 // Handles request to override default use of A2DP for media.
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005187 // Must be called synchronized on mConnectedDevices
Eric Laurent78472112012-05-21 08:57:21 -07005188 public void setBluetoothA2dpOnInt(boolean on) {
5189 synchronized (mBluetoothA2dpEnabledLock) {
5190 mBluetoothA2dpEnabled = on;
Eric Laurentc390bed2012-07-03 12:24:05 -07005191 mAudioHandler.removeMessages(MSG_SET_FORCE_BT_A2DP_USE);
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005192 setForceUseInt_SyncDevices(AudioSystem.FOR_MEDIA,
Eric Laurentc390bed2012-07-03 12:24:05 -07005193 mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP);
Eric Laurent78472112012-05-21 08:57:21 -07005194 }
5195 }
5196
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005197 // Must be called synchronized on mConnectedDevices
5198 private void setForceUseInt_SyncDevices(int usage, int config) {
5199 switch (usage) {
5200 case AudioSystem.FOR_MEDIA:
5201 if (config == AudioSystem.FORCE_NO_BT_A2DP) {
5202 mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ALL_A2DP;
5203 } else { // config == AudioSystem.FORCE_NONE
5204 mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ALL_A2DP;
5205 }
5206 break;
5207 case AudioSystem.FOR_DOCK:
5208 if (config == AudioSystem.FORCE_ANALOG_DOCK) {
5209 mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
5210 } else { // config == AudioSystem.FORCE_NONE
5211 mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
5212 }
5213 break;
5214 default:
5215 // usage doesn't affect the broadcast of ACTION_AUDIO_BECOMING_NOISY
5216 }
5217 AudioSystem.setForceUse(usage, config);
5218 }
5219
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005220 @Override
Jeff Sharkey098d5802012-04-26 17:30:34 -07005221 public void setRingtonePlayer(IRingtonePlayer player) {
5222 mContext.enforceCallingOrSelfPermission(REMOTE_AUDIO_PLAYBACK, null);
5223 mRingtonePlayer = player;
5224 }
5225
5226 @Override
5227 public IRingtonePlayer getRingtonePlayer() {
5228 return mRingtonePlayer;
5229 }
5230
5231 @Override
Dianne Hackborn632ca412012-06-14 19:34:10 -07005232 public AudioRoutesInfo startWatchingRoutes(IAudioRoutesObserver observer) {
5233 synchronized (mCurAudioRoutes) {
5234 AudioRoutesInfo routes = new AudioRoutesInfo(mCurAudioRoutes);
5235 mRoutesObservers.register(observer);
5236 return routes;
5237 }
5238 }
5239
Eric Laurentc34dcc12012-09-10 13:51:52 -07005240
5241 //==========================================================================================
5242 // Safe media volume management.
5243 // MUSIC stream volume level is limited when headphones are connected according to safety
5244 // regulation. When the user attempts to raise the volume above the limit, a warning is
5245 // displayed and the user has to acknowlegde before the volume is actually changed.
5246 // The volume index corresponding to the limit is stored in config_safe_media_volume_index
5247 // property. Platforms with a different limit must set this property accordingly in their
5248 // overlay.
5249 //==========================================================================================
5250
Eric Laurentd640bd32012-09-28 18:01:48 -07005251 // mSafeMediaVolumeState indicates whether the media volume is limited over headphones.
5252 // It is SAFE_MEDIA_VOLUME_NOT_CONFIGURED at boot time until a network service is connected
5253 // or the configure time is elapsed. It is then set to SAFE_MEDIA_VOLUME_ACTIVE or
5254 // SAFE_MEDIA_VOLUME_DISABLED according to country option. If not SAFE_MEDIA_VOLUME_DISABLED, it
5255 // can be set to SAFE_MEDIA_VOLUME_INACTIVE by calling AudioService.disableSafeMediaVolume()
5256 // (when user opts out).
John Spurlock35134602014-07-24 18:10:48 -04005257 private static final int SAFE_MEDIA_VOLUME_NOT_CONFIGURED = 0;
5258 private static final int SAFE_MEDIA_VOLUME_DISABLED = 1;
5259 private static final int SAFE_MEDIA_VOLUME_INACTIVE = 2; // confirmed
5260 private static final int SAFE_MEDIA_VOLUME_ACTIVE = 3; // unconfirmed
Eric Laurentd640bd32012-09-28 18:01:48 -07005261 private Integer mSafeMediaVolumeState;
5262
5263 private int mMcc = 0;
Eric Laurentc34dcc12012-09-10 13:51:52 -07005264 // mSafeMediaVolumeIndex is the cached value of config_safe_media_volume_index property
Eric Laurentd640bd32012-09-28 18:01:48 -07005265 private int mSafeMediaVolumeIndex;
Eric Laurentc34dcc12012-09-10 13:51:52 -07005266 // mSafeMediaVolumeDevices lists the devices for which safe media volume is enforced,
5267 private final int mSafeMediaVolumeDevices = AudioSystem.DEVICE_OUT_WIRED_HEADSET |
5268 AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
5269 // mMusicActiveMs is the cumulative time of music activity since safe volume was disabled.
5270 // When this time reaches UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX, the safe media volume is re-enabled
5271 // automatically. mMusicActiveMs is rounded to a multiple of MUSIC_ACTIVE_POLL_PERIOD_MS.
5272 private int mMusicActiveMs;
5273 private static final int UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX = (20 * 3600 * 1000); // 20 hours
5274 private static final int MUSIC_ACTIVE_POLL_PERIOD_MS = 60000; // 1 minute polling interval
Eric Laurentd640bd32012-09-28 18:01:48 -07005275 private static final int SAFE_VOLUME_CONFIGURE_TIMEOUT_MS = 30000; // 30s after boot completed
Eric Laurentc34dcc12012-09-10 13:51:52 -07005276
5277 private void setSafeMediaVolumeEnabled(boolean on) {
Eric Laurentd640bd32012-09-28 18:01:48 -07005278 synchronized (mSafeMediaVolumeState) {
5279 if ((mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_NOT_CONFIGURED) &&
5280 (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_DISABLED)) {
5281 if (on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE)) {
5282 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE;
5283 enforceSafeMediaVolume();
5284 } else if (!on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE)) {
5285 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE;
John Spurlockaa5ee4d2014-07-25 13:05:12 -04005286 mMusicActiveMs = 1; // nonzero = confirmed
5287 saveMusicActiveMs();
Eric Laurentd640bd32012-09-28 18:01:48 -07005288 sendMsg(mAudioHandler,
5289 MSG_CHECK_MUSIC_ACTIVE,
5290 SENDMSG_REPLACE,
5291 0,
5292 0,
5293 null,
5294 MUSIC_ACTIVE_POLL_PERIOD_MS);
5295 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005296 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005297 }
5298 }
5299
5300 private void enforceSafeMediaVolume() {
5301 VolumeStreamState streamState = mStreamStates[AudioSystem.STREAM_MUSIC];
Eric Laurentc34dcc12012-09-10 13:51:52 -07005302 int devices = mSafeMediaVolumeDevices;
5303 int i = 0;
5304
5305 while (devices != 0) {
5306 int device = 1 << i++;
5307 if ((device & devices) == 0) {
5308 continue;
5309 }
Eric Laurent42b041e2013-03-29 11:36:03 -07005310 int index = streamState.getIndex(device);
Eric Laurentc34dcc12012-09-10 13:51:52 -07005311 if (index > mSafeMediaVolumeIndex) {
Eric Laurent42b041e2013-03-29 11:36:03 -07005312 streamState.setIndex(mSafeMediaVolumeIndex, device);
5313 sendMsg(mAudioHandler,
5314 MSG_SET_DEVICE_VOLUME,
5315 SENDMSG_QUEUE,
5316 device,
5317 0,
5318 streamState,
5319 0);
Eric Laurentc34dcc12012-09-10 13:51:52 -07005320 }
5321 devices &= ~device;
5322 }
5323 }
5324
5325 private boolean checkSafeMediaVolume(int streamType, int index, int device) {
Eric Laurentd640bd32012-09-28 18:01:48 -07005326 synchronized (mSafeMediaVolumeState) {
5327 if ((mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) &&
Eric Laurentc34dcc12012-09-10 13:51:52 -07005328 (mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) &&
5329 ((device & mSafeMediaVolumeDevices) != 0) &&
5330 (index > mSafeMediaVolumeIndex)) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07005331 return false;
5332 }
5333 return true;
5334 }
5335 }
5336
John Spurlock3346a802014-05-20 16:25:37 -04005337 @Override
Eric Laurentc34dcc12012-09-10 13:51:52 -07005338 public void disableSafeMediaVolume() {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005339 enforceVolumeController("disable the safe media volume");
Eric Laurentd640bd32012-09-28 18:01:48 -07005340 synchronized (mSafeMediaVolumeState) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07005341 setSafeMediaVolumeEnabled(false);
Eric Laurentfde16d52012-12-03 14:42:39 -08005342 if (mPendingVolumeCommand != null) {
5343 onSetStreamVolume(mPendingVolumeCommand.mStreamType,
5344 mPendingVolumeCommand.mIndex,
5345 mPendingVolumeCommand.mFlags,
5346 mPendingVolumeCommand.mDevice);
5347 mPendingVolumeCommand = null;
5348 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005349 }
5350 }
5351
Jungshik Jang41d97462014-06-30 22:26:29 +09005352 //==========================================================================================
5353 // Hdmi Cec system audio mode.
5354 // If Hdmi Cec's system audio mode is on, audio service should notify volume change
5355 // to HdmiControlService so that audio recevier can handle volume change.
5356 //==========================================================================================
5357
Eric Laurent212532b2014-07-21 15:43:18 -07005358 private class MyDisplayStatusCallback implements HdmiPlaybackClient.DisplayStatusCallback {
5359 public void onComplete(int status) {
5360 if (mHdmiManager != null) {
5361 synchronized (mHdmiManager) {
5362 mHdmiCecSink = (status != HdmiControlManager.POWER_STATUS_UNKNOWN);
5363 // Television devices without CEC service apply software volume on HDMI output
5364 if (isPlatformTelevision() && !mHdmiCecSink) {
5365 mFixedVolumeDevices &= ~AudioSystem.DEVICE_OUT_HDMI;
5366 }
5367 checkAllFixedVolumeDevices();
5368 }
5369 }
5370 }
5371 };
5372
Jungshik Jang41d97462014-06-30 22:26:29 +09005373 // If HDMI-CEC system audio is supported
5374 private boolean mHdmiSystemAudioSupported = false;
5375 // Set only when device is tv.
5376 private HdmiTvClient mHdmiTvClient;
Eric Laurent0b03f992014-11-18 18:08:02 -08005377 // true if the device has system feature PackageManager.FEATURE_LEANBACK.
Eric Laurent212532b2014-07-21 15:43:18 -07005378 // cached HdmiControlManager interface
5379 private HdmiControlManager mHdmiManager;
5380 // Set only when device is a set-top box.
5381 private HdmiPlaybackClient mHdmiPlaybackClient;
5382 // true if we are a set-top box, an HDMI sink is connected and it supports CEC.
5383 private boolean mHdmiCecSink;
5384
5385 private MyDisplayStatusCallback mHdmiDisplayStatusCallback = new MyDisplayStatusCallback();
Jungshik Jang41d97462014-06-30 22:26:29 +09005386
5387 @Override
Jungshik Jang12307ca2014-07-15 19:27:56 +09005388 public int setHdmiSystemAudioSupported(boolean on) {
Eric Laurent212532b2014-07-21 15:43:18 -07005389 int device = AudioSystem.DEVICE_NONE;
5390 if (mHdmiManager != null) {
5391 synchronized (mHdmiManager) {
5392 if (mHdmiTvClient == null) {
5393 Log.w(TAG, "Only Hdmi-Cec enabled TV device supports system audio mode.");
5394 return device;
5395 }
Jungshik Jang41d97462014-06-30 22:26:29 +09005396
Eric Laurent212532b2014-07-21 15:43:18 -07005397 synchronized (mHdmiTvClient) {
5398 if (mHdmiSystemAudioSupported != on) {
5399 mHdmiSystemAudioSupported = on;
5400 AudioSystem.setForceUse(AudioSystem.FOR_HDMI_SYSTEM_AUDIO,
5401 on ? AudioSystem.FORCE_HDMI_SYSTEM_AUDIO_ENFORCED :
5402 AudioSystem.FORCE_NONE);
5403 }
5404 device = AudioSystem.getDevicesForStream(AudioSystem.STREAM_MUSIC);
5405 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005406 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005407 }
Eric Laurent212532b2014-07-21 15:43:18 -07005408 return device;
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005409 }
Jungshik Jang41d97462014-06-30 22:26:29 +09005410
Terry Heoe7d6d972014-09-04 21:05:28 +09005411 @Override
5412 public boolean isHdmiSystemAudioSupported() {
5413 return mHdmiSystemAudioSupported;
5414 }
5415
Eric Laurentdd45d012012-10-08 09:04:34 -07005416 //==========================================================================================
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07005417 // Accessibility: taking touch exploration into account for selecting the default
5418 // stream override timeout when adjusting volume
5419 //==========================================================================================
5420 private static class StreamOverride
5421 implements AccessibilityManager.TouchExplorationStateChangeListener {
5422
5423 // AudioService.getActiveStreamType() will return:
5424 // - STREAM_NOTIFICATION on tablets during this period after a notification stopped
5425 // - STREAM_MUSIC on phones during this period after music or talkback/voice search prompt
5426 // stopped
5427 private static final int DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS = 5000;
5428 private static final int TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS = 1000;
5429
5430 static int sDelayMs;
5431
5432 static void init(Context ctxt) {
5433 AccessibilityManager accessibilityManager =
5434 (AccessibilityManager) ctxt.getSystemService(Context.ACCESSIBILITY_SERVICE);
5435 updateDefaultStreamOverrideDelay(
5436 accessibilityManager.isTouchExplorationEnabled());
5437 accessibilityManager.addTouchExplorationStateChangeListener(
5438 new StreamOverride());
5439 }
5440
5441 @Override
5442 public void onTouchExplorationStateChanged(boolean enabled) {
5443 updateDefaultStreamOverrideDelay(enabled);
5444 }
5445
5446 private static void updateDefaultStreamOverrideDelay(boolean touchExploreEnabled) {
5447 if (touchExploreEnabled) {
5448 sDelayMs = TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS;
5449 } else {
5450 sDelayMs = DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS;
5451 }
5452 if (DEBUG_VOL) Log.d(TAG, "Touch exploration enabled=" + touchExploreEnabled
5453 + " stream override delay is now " + sDelayMs + " ms");
5454 }
5455 }
5456
5457 //==========================================================================================
Eric Laurentdd45d012012-10-08 09:04:34 -07005458 // Camera shutter sound policy.
5459 // config_camera_sound_forced configuration option in config.xml defines if the camera shutter
5460 // sound is forced (sound even if the device is in silent mode) or not. This option is false by
5461 // default and can be overridden by country specific overlay in values-mccXXX/config.xml.
5462 //==========================================================================================
5463
5464 // cached value of com.android.internal.R.bool.config_camera_sound_forced
5465 private Boolean mCameraSoundForced;
5466
5467 // called by android.hardware.Camera to populate CameraInfo.canDisableShutterSound
5468 public boolean isCameraSoundForced() {
5469 synchronized (mCameraSoundForced) {
5470 return mCameraSoundForced;
5471 }
5472 }
5473
5474 private static final String[] RINGER_MODE_NAMES = new String[] {
5475 "SILENT",
5476 "VIBRATE",
5477 "NORMAL"
5478 };
5479
5480 private void dumpRingerMode(PrintWriter pw) {
5481 pw.println("\nRinger mode: ");
John Spurlock661f2cf2014-11-17 10:29:10 -05005482 pw.println("- mode (internal) = " + RINGER_MODE_NAMES[mRingerMode]);
5483 pw.println("- mode (external) = " + RINGER_MODE_NAMES[mRingerModeExternal]);
Eric Laurentdd45d012012-10-08 09:04:34 -07005484 pw.print("- ringer mode affected streams = 0x");
5485 pw.println(Integer.toHexString(mRingerModeAffectedStreams));
5486 pw.print("- ringer mode muted streams = 0x");
5487 pw.println(Integer.toHexString(mRingerModeMutedStreams));
John Spurlock661f2cf2014-11-17 10:29:10 -05005488 pw.print("- delegate = "); pw.println(mRingerModeDelegate);
Eric Laurentdd45d012012-10-08 09:04:34 -07005489 }
5490
Dianne Hackborn632ca412012-06-14 19:34:10 -07005491 @Override
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005492 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005493 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5494
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005495 mMediaFocusControl.dump(pw);
Eric Laurentbffc3d12012-05-07 17:43:49 -07005496 dumpStreamStates(pw);
Eric Laurentdd45d012012-10-08 09:04:34 -07005497 dumpRingerMode(pw);
Dianne Hackborn632ca412012-06-14 19:34:10 -07005498 pw.println("\nAudio routes:");
John Spurlock61560172015-02-06 19:46:04 -05005499 pw.print(" mMainType=0x"); pw.println(Integer.toHexString(mCurAudioRoutes.mainType));
5500 pw.print(" mBluetoothName="); pw.println(mCurAudioRoutes.bluetoothName);
John Spurlock35134602014-07-24 18:10:48 -04005501
5502 pw.println("\nOther state:");
John Spurlock3346a802014-05-20 16:25:37 -04005503 pw.print(" mVolumeController="); pw.println(mVolumeController);
John Spurlock35134602014-07-24 18:10:48 -04005504 pw.print(" mSafeMediaVolumeState=");
5505 pw.println(safeMediaVolumeStateToString(mSafeMediaVolumeState));
5506 pw.print(" mSafeMediaVolumeIndex="); pw.println(mSafeMediaVolumeIndex);
5507 pw.print(" mPendingVolumeCommand="); pw.println(mPendingVolumeCommand);
5508 pw.print(" mMusicActiveMs="); pw.println(mMusicActiveMs);
John Spurlockaa5ee4d2014-07-25 13:05:12 -04005509 pw.print(" mMcc="); pw.println(mMcc);
John Spurlock661f2cf2014-11-17 10:29:10 -05005510 pw.print(" mHasVibrator="); pw.println(mHasVibrator);
John Spurlockcdb57ae2015-02-11 19:04:11 -05005511 pw.print(" mControllerService="); pw.println(mControllerService);
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005512
5513 dumpAudioPolicies(pw);
John Spurlock35134602014-07-24 18:10:48 -04005514 }
5515
5516 private static String safeMediaVolumeStateToString(Integer state) {
5517 switch(state) {
5518 case SAFE_MEDIA_VOLUME_NOT_CONFIGURED: return "SAFE_MEDIA_VOLUME_NOT_CONFIGURED";
5519 case SAFE_MEDIA_VOLUME_DISABLED: return "SAFE_MEDIA_VOLUME_DISABLED";
5520 case SAFE_MEDIA_VOLUME_INACTIVE: return "SAFE_MEDIA_VOLUME_INACTIVE";
5521 case SAFE_MEDIA_VOLUME_ACTIVE: return "SAFE_MEDIA_VOLUME_ACTIVE";
5522 }
5523 return null;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005524 }
Glenn Kastenfd116ad2013-07-12 17:10:39 -07005525
5526 // Inform AudioFlinger of our device's low RAM attribute
5527 private static void readAndSetLowRamDevice()
5528 {
5529 int status = AudioSystem.setLowRamDevice(ActivityManager.isLowRamDeviceStatic());
5530 if (status != 0) {
5531 Log.w(TAG, "AudioFlinger informed of device's low RAM attribute; status " + status);
5532 }
5533 }
John Spurlock3346a802014-05-20 16:25:37 -04005534
John Spurlockcdb57ae2015-02-11 19:04:11 -05005535 private void enforceVolumeController(String action) {
5536 if (mControllerService.mUid != 0 && Binder.getCallingUid() == mControllerService.mUid) {
5537 return;
5538 }
John Spurlock3346a802014-05-20 16:25:37 -04005539 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
5540 "Only SystemUI can " + action);
5541 }
5542
5543 @Override
5544 public void setVolumeController(final IVolumeController controller) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005545 enforceVolumeController("set the volume controller");
John Spurlock3346a802014-05-20 16:25:37 -04005546
5547 // return early if things are not actually changing
5548 if (mVolumeController.isSameBinder(controller)) {
5549 return;
5550 }
5551
5552 // dismiss the old volume controller
5553 mVolumeController.postDismiss();
5554 if (controller != null) {
5555 // we are about to register a new controller, listen for its death
5556 try {
5557 controller.asBinder().linkToDeath(new DeathRecipient() {
5558 @Override
5559 public void binderDied() {
5560 if (mVolumeController.isSameBinder(controller)) {
5561 Log.w(TAG, "Current remote volume controller died, unregistering");
5562 setVolumeController(null);
5563 }
5564 }
5565 }, 0);
5566 } catch (RemoteException e) {
5567 // noop
5568 }
5569 }
5570 mVolumeController.setController(controller);
John Spurlock33f4e042014-07-11 13:10:58 -04005571 if (DEBUG_VOL) Log.d(TAG, "Volume controller: " + mVolumeController);
5572 }
5573
5574 @Override
5575 public void notifyVolumeControllerVisible(final IVolumeController controller, boolean visible) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005576 enforceVolumeController("notify about volume controller visibility");
John Spurlock33f4e042014-07-11 13:10:58 -04005577
5578 // return early if the controller is not current
5579 if (!mVolumeController.isSameBinder(controller)) {
5580 return;
5581 }
5582
5583 mVolumeController.setVisible(visible);
5584 if (DEBUG_VOL) Log.d(TAG, "Volume controller visible: " + visible);
John Spurlock3346a802014-05-20 16:25:37 -04005585 }
RoboErikd09bd0c2014-06-24 17:45:19 -07005586
5587 public static class VolumeController {
5588 private static final String TAG = "VolumeController";
5589
5590 private IVolumeController mController;
John Spurlock33f4e042014-07-11 13:10:58 -04005591 private boolean mVisible;
5592 private long mNextLongPress;
5593 private int mLongPressTimeout;
RoboErikd09bd0c2014-06-24 17:45:19 -07005594
5595 public void setController(IVolumeController controller) {
5596 mController = controller;
John Spurlock33f4e042014-07-11 13:10:58 -04005597 mVisible = false;
5598 }
5599
5600 public void loadSettings(ContentResolver cr) {
5601 mLongPressTimeout = Settings.Secure.getIntForUser(cr,
5602 Settings.Secure.LONG_PRESS_TIMEOUT, 500, UserHandle.USER_CURRENT);
5603 }
5604
RoboErik4197cb62015-01-21 15:45:32 -08005605 public boolean suppressAdjustment(int resolvedStream, int flags, boolean isMute) {
5606 if (isMute) {
5607 return false;
5608 }
John Spurlock33f4e042014-07-11 13:10:58 -04005609 boolean suppress = false;
5610 if (resolvedStream == AudioSystem.STREAM_RING && mController != null) {
5611 final long now = SystemClock.uptimeMillis();
5612 if ((flags & AudioManager.FLAG_SHOW_UI) != 0 && !mVisible) {
5613 // ui will become visible
5614 if (mNextLongPress < now) {
5615 mNextLongPress = now + mLongPressTimeout;
5616 }
5617 suppress = true;
5618 } else if (mNextLongPress > 0) { // in a long-press
5619 if (now > mNextLongPress) {
5620 // long press triggered, no more suppression
5621 mNextLongPress = 0;
5622 } else {
5623 // keep suppressing until the long press triggers
5624 suppress = true;
5625 }
5626 }
5627 }
5628 return suppress;
5629 }
5630
5631 public void setVisible(boolean visible) {
5632 mVisible = visible;
RoboErikd09bd0c2014-06-24 17:45:19 -07005633 }
5634
5635 public boolean isSameBinder(IVolumeController controller) {
5636 return Objects.equals(asBinder(), binder(controller));
5637 }
5638
5639 public IBinder asBinder() {
5640 return binder(mController);
5641 }
5642
5643 private static IBinder binder(IVolumeController controller) {
5644 return controller == null ? null : controller.asBinder();
5645 }
5646
5647 @Override
5648 public String toString() {
John Spurlock33f4e042014-07-11 13:10:58 -04005649 return "VolumeController(" + asBinder() + ",mVisible=" + mVisible + ")";
RoboErikd09bd0c2014-06-24 17:45:19 -07005650 }
5651
5652 public void postDisplaySafeVolumeWarning(int flags) {
5653 if (mController == null)
5654 return;
5655 try {
5656 mController.displaySafeVolumeWarning(flags);
5657 } catch (RemoteException e) {
5658 Log.w(TAG, "Error calling displaySafeVolumeWarning", e);
5659 }
5660 }
5661
5662 public void postVolumeChanged(int streamType, int flags) {
5663 if (mController == null)
5664 return;
5665 try {
5666 mController.volumeChanged(streamType, flags);
5667 } catch (RemoteException e) {
5668 Log.w(TAG, "Error calling volumeChanged", e);
5669 }
5670 }
5671
5672 public void postMasterVolumeChanged(int flags) {
5673 if (mController == null)
5674 return;
5675 try {
5676 mController.masterVolumeChanged(flags);
5677 } catch (RemoteException e) {
5678 Log.w(TAG, "Error calling masterVolumeChanged", e);
5679 }
5680 }
5681
5682 public void postMasterMuteChanged(int flags) {
5683 if (mController == null)
5684 return;
5685 try {
5686 mController.masterMuteChanged(flags);
5687 } catch (RemoteException e) {
5688 Log.w(TAG, "Error calling masterMuteChanged", e);
5689 }
5690 }
5691
5692 public void setLayoutDirection(int layoutDirection) {
5693 if (mController == null)
5694 return;
5695 try {
5696 mController.setLayoutDirection(layoutDirection);
5697 } catch (RemoteException e) {
5698 Log.w(TAG, "Error calling setLayoutDirection", e);
5699 }
5700 }
5701
5702 public void postDismiss() {
5703 if (mController == null)
5704 return;
5705 try {
5706 mController.dismiss();
5707 } catch (RemoteException e) {
5708 Log.w(TAG, "Error calling dismiss", e);
5709 }
5710 }
5711 }
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005712
RoboErik0dac35a2014-08-12 15:48:49 -07005713 /**
5714 * Interface for system components to get some extra functionality through
5715 * LocalServices.
5716 */
5717 final class AudioServiceInternal extends AudioManagerInternal {
John Spurlock661f2cf2014-11-17 10:29:10 -05005718 @Override
5719 public void setRingerModeDelegate(RingerModeDelegate delegate) {
5720 mRingerModeDelegate = delegate;
5721 if (mRingerModeDelegate != null) {
5722 setRingerModeInternal(getRingerModeInternal(), TAG + ".setRingerModeDelegate");
5723 }
5724 }
RoboErik272e1612014-09-05 11:39:29 -07005725
5726 @Override
5727 public void adjustSuggestedStreamVolumeForUid(int streamType, int direction, int flags,
5728 String callingPackage, int uid) {
5729 // direction and stream type swap here because the public
5730 // adjustSuggested has a different order than the other methods.
5731 adjustSuggestedStreamVolume(direction, streamType, flags, callingPackage, uid);
5732 }
5733
RoboErik0dac35a2014-08-12 15:48:49 -07005734 @Override
5735 public void adjustStreamVolumeForUid(int streamType, int direction, int flags,
5736 String callingPackage, int uid) {
5737 adjustStreamVolume(streamType, direction, flags, callingPackage, uid);
5738 }
5739
5740 @Override
5741 public void setStreamVolumeForUid(int streamType, int direction, int flags,
5742 String callingPackage, int uid) {
5743 setStreamVolume(streamType, direction, flags, callingPackage, uid);
5744 }
RoboErik519c7742014-11-18 10:59:09 -08005745
5746 @Override
5747 public void adjustMasterVolumeForUid(int steps, int flags, String callingPackage,
5748 int uid) {
5749 adjustMasterVolume(steps, flags, callingPackage, uid);
5750 }
John Spurlock661f2cf2014-11-17 10:29:10 -05005751
5752 @Override
5753 public int getRingerModeInternal() {
5754 return AudioService.this.getRingerModeInternal();
5755 }
5756
5757 @Override
5758 public void setRingerModeInternal(int ringerMode, String caller) {
5759 AudioService.this.setRingerModeInternal(ringerMode, caller);
5760 }
John Spurlockcdb57ae2015-02-11 19:04:11 -05005761
5762 @Override
5763 public int getVolumeControllerUid() {
5764 return mControllerService.mUid;
5765 }
RoboErik0dac35a2014-08-12 15:48:49 -07005766 }
5767
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005768 //==========================================================================================
5769 // Audio policy management
5770 //==========================================================================================
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005771 public String registerAudioPolicy(AudioPolicyConfig policyConfig, IAudioPolicyCallback pcb,
5772 boolean hasFocusListener) {
5773 if (DEBUG_AP) Log.d(TAG, "registerAudioPolicy for " + pcb.asBinder()
5774 + " with config:" + policyConfig);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005775 String regId = null;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005776 // error handling
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005777 boolean hasPermissionForPolicy =
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005778 (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission(
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005779 android.Manifest.permission.MODIFY_AUDIO_ROUTING));
5780 if (!hasPermissionForPolicy) {
5781 Slog.w(TAG, "Can't register audio policy for pid " + Binder.getCallingPid() + " / uid "
5782 + Binder.getCallingUid() + ", need MODIFY_AUDIO_ROUTING");
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005783 return null;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005784 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005785
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005786 synchronized (mAudioPolicies) {
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005787 try {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005788 if (mAudioPolicies.containsKey(pcb.asBinder())) {
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005789 Slog.e(TAG, "Cannot re-register policy");
5790 return null;
5791 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005792 AudioPolicyProxy app = new AudioPolicyProxy(policyConfig, pcb, hasFocusListener);
5793 pcb.asBinder().linkToDeath(app, 0/*flags*/);
5794 regId = app.getRegistrationId();
5795 mAudioPolicies.put(pcb.asBinder(), app);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005796 } catch (RemoteException e) {
5797 // audio policy owner has already died!
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005798 Slog.w(TAG, "Audio policy registration failed, could not link to " + pcb +
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005799 " binder death", e);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005800 return null;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005801 }
5802 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005803 return regId;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005804 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005805
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005806 public void unregisterAudioPolicyAsync(IAudioPolicyCallback pcb) {
5807 if (DEBUG_AP) Log.d(TAG, "unregisterAudioPolicyAsync for " + pcb.asBinder());
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005808 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005809 AudioPolicyProxy app = mAudioPolicies.remove(pcb.asBinder());
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005810 if (app == null) {
5811 Slog.w(TAG, "Trying to unregister unknown audio policy for pid "
5812 + Binder.getCallingPid() + " / uid " + Binder.getCallingUid());
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005813 return;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005814 } else {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005815 pcb.asBinder().unlinkToDeath(app, 0/*flags*/);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005816 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005817 app.release();
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005818 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005819 // TODO implement clearing mix attribute matching info in native audio policy
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005820 }
5821
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005822 public int setFocusPropertiesForPolicy(int duckingBehavior, IAudioPolicyCallback pcb) {
5823 if (DEBUG_AP) Log.d(TAG, "setFocusPropertiesForPolicy() duck behavior=" + duckingBehavior
5824 + " policy " + pcb.asBinder());
5825 // error handling
5826 boolean hasPermissionForPolicy =
5827 (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission(
5828 android.Manifest.permission.MODIFY_AUDIO_ROUTING));
5829 if (!hasPermissionForPolicy) {
5830 Slog.w(TAG, "Cannot change audio policy ducking handling for pid " +
5831 + Binder.getCallingPid() + " / uid "
5832 + Binder.getCallingUid() + ", need MODIFY_AUDIO_ROUTING");
5833 return AudioManager.ERROR;
5834 }
5835
5836 synchronized (mAudioPolicies) {
5837 if (!mAudioPolicies.containsKey(pcb.asBinder())) {
5838 Slog.e(TAG, "Cannot change audio policy focus properties, unregistered policy");
5839 return AudioManager.ERROR;
5840 }
5841 final AudioPolicyProxy app = mAudioPolicies.get(pcb.asBinder());
5842 if (duckingBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5843 // is there already one policy managing ducking?
5844 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
5845 if (policy.mFocusDuckBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5846 Slog.e(TAG, "Cannot change audio policy ducking behavior, already handled");
5847 return AudioManager.ERROR;
5848 }
5849 }
5850 }
5851 app.mFocusDuckBehavior = duckingBehavior;
5852 mMediaFocusControl.setDuckingInExtPolicyAvailable(
5853 duckingBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY);
5854 }
5855 return AudioManager.SUCCESS;
5856 }
5857
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005858 private void dumpAudioPolicies(PrintWriter pw) {
5859 pw.println("\nAudio policies:");
5860 synchronized (mAudioPolicies) {
5861 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
5862 pw.println(policy.toLogFriendlyString());
5863 }
5864 }
5865 }
5866
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005867 //======================
5868 // Audio policy proxy
5869 //======================
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005870 /**
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005871 * This internal class inherits from AudioPolicyConfig, each instance contains all the
5872 * mixes of an AudioPolicy and their configurations.
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005873 */
5874 public class AudioPolicyProxy extends AudioPolicyConfig implements IBinder.DeathRecipient {
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005875 private static final String TAG = "AudioPolicyProxy";
5876 AudioPolicyConfig mConfig;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005877 IAudioPolicyCallback mPolicyToken;
5878 boolean mHasFocusListener;
5879 /**
5880 * Audio focus ducking behavior for an audio policy.
5881 * This variable reflects the value that was successfully set in
5882 * {@link AudioService#setFocusPropertiesForPolicy(int, IAudioPolicyCallback)}. This
5883 * implies that a value of FOCUS_POLICY_DUCKING_IN_POLICY means the corresponding policy
5884 * is handling ducking for audio focus.
5885 */
5886 int mFocusDuckBehavior = AudioPolicy.FOCUS_POLICY_DUCKING_DEFAULT;
5887
5888 AudioPolicyProxy(AudioPolicyConfig config, IAudioPolicyCallback token,
5889 boolean hasFocusListener) {
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005890 super(config);
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005891 setRegistration(new String(config.hashCode() + ":ap:" + mAudioPolicyCounter++));
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005892 mPolicyToken = token;
5893 mHasFocusListener = hasFocusListener;
5894 if (mHasFocusListener) {
5895 mMediaFocusControl.addFocusFollower(mPolicyToken);
5896 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005897 connectMixes();
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005898 }
5899
5900 public void binderDied() {
5901 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005902 Log.i(TAG, "audio policy " + mPolicyToken + " died");
5903 release();
5904 mAudioPolicies.remove(mPolicyToken.asBinder());
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005905 }
5906 }
5907
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005908 String getRegistrationId() {
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005909 return getRegistration();
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005910 }
5911
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005912 void release() {
5913 if (mFocusDuckBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5914 mMediaFocusControl.setDuckingInExtPolicyAvailable(false);
5915 }
5916 if (mHasFocusListener) {
5917 mMediaFocusControl.removeFocusFollower(mPolicyToken);
5918 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005919 AudioSystem.registerPolicyMixes(mMixes, false);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005920 }
5921
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005922 void connectMixes() {
5923 AudioSystem.registerPolicyMixes(mMixes, true);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005924 }
5925 };
5926
5927 private HashMap<IBinder, AudioPolicyProxy> mAudioPolicies =
5928 new HashMap<IBinder, AudioPolicyProxy>();
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005929 private int mAudioPolicyCounter = 0; // always accessed synchronized on mAudioPolicies
John Spurlockcdb57ae2015-02-11 19:04:11 -05005930
5931 private class ControllerService extends ContentObserver {
5932 private int mUid;
5933 private ComponentName mComponent;
5934
5935 public ControllerService() {
5936 super(null);
5937 }
5938
5939 @Override
5940 public String toString() {
5941 return String.format("{mUid=%d,mComponent=%s}", mUid, mComponent);
5942 }
5943
5944 public void init() {
5945 onChange(true);
5946 mContentResolver.registerContentObserver(Settings.Secure.getUriFor(
5947 Settings.Secure.VOLUME_CONTROLLER_SERVICE_COMPONENT), false, this);
5948 }
5949
5950 @Override
5951 public void onChange(boolean selfChange) {
5952 mUid = 0;
5953 mComponent = null;
5954 final String setting = Settings.Secure.getString(mContentResolver,
5955 Settings.Secure.VOLUME_CONTROLLER_SERVICE_COMPONENT);
5956 if (setting == null) return;
5957 try {
5958 mComponent = ComponentName.unflattenFromString(setting);
5959 if (mComponent == null) return;
5960 mUid = mContext.getPackageManager()
5961 .getApplicationInfo(mComponent.getPackageName(), 0).uid;
5962 } catch (Exception e) {
5963 Log.w(TAG, "Error loading controller service", e);
5964 }
5965 if (DEBUG_VOL) Log.d(TAG, "Reloaded controller service: " + this);
5966 }
5967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968}