blob: afe7d7a1573000e877ff588d17ac2a2bde4461db [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
John Spurlock3ce37252015-02-17 13:20:45 -0500373 /** Streams that can be muted. Do not resolve to aliases when checking.
374 * @see System#MUTE_STREAMS_AFFECTED */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 private int mMuteAffectedStreams;
376
377 /**
Eric Laurentbffc3d12012-05-07 17:43:49 -0700378 * NOTE: setVibrateSetting(), getVibrateSetting(), shouldVibrate() are deprecated.
379 * mVibrateSetting is just maintained during deprecation period but vibration policy is
380 * now only controlled by mHasVibrator and mRingerMode
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 */
382 private int mVibrateSetting;
383
Eric Laurentbffc3d12012-05-07 17:43:49 -0700384 // Is there a vibrator
385 private final boolean mHasVibrator;
386
Eric Laurenta553c252009-07-17 12:17:14 -0700387 // Broadcast receiver for device connections intent broadcasts
388 private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
389
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700390 // Devices currently connected
Glenn Kasten30c918c2011-11-10 17:56:41 -0800391 private final HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700392
393 // Forced device usage for communications
394 private int mForcedUseForComm;
395
Mike Lockwood0dc37cc2011-12-01 16:14:19 -0500396 // True if we have master volume support
397 private final boolean mUseMasterVolume;
398
Mike Lockwood97606472012-02-09 11:24:10 -0800399 private final int[] mMasterVolumeRamp;
400
Eric Laurent9272b4b2010-01-23 17:12:59 -0800401 // List of binder death handlers for setMode() client processes.
402 // The last process to have called setMode() is at the top of the list.
Glenn Kasten30c918c2011-11-10 17:56:41 -0800403 private final ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
Eric Laurenteb14a782009-12-17 03:12:59 -0800404
Eric Laurent3def1ee2010-03-17 23:26:26 -0700405 // List of clients having issued a SCO start request
Glenn Kasten30c918c2011-11-10 17:56:41 -0800406 private final ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
Eric Laurent3def1ee2010-03-17 23:26:26 -0700407
408 // BluetoothHeadset API to control SCO connection
409 private BluetoothHeadset mBluetoothHeadset;
410
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700411 // Bluetooth headset device
412 private BluetoothDevice mBluetoothHeadsetDevice;
Eric Laurent3def1ee2010-03-17 23:26:26 -0700413
Eric Laurent62ef7672010-11-24 10:58:32 -0800414 // Indicate if SCO audio connection is currently active and if the initiator is
415 // audio service (internal) or bluetooth headset (external)
416 private int mScoAudioState;
417 // SCO audio state is not active
418 private static final int SCO_STATE_INACTIVE = 0;
Eric Laurentdc03c612011-04-01 10:59:41 -0700419 // SCO audio activation request waiting for headset service to connect
420 private static final int SCO_STATE_ACTIVATE_REQ = 1;
Eric Laurent25fc29b2013-04-05 12:13:54 -0700421 // SCO audio state is active or starting due to a request from AudioManager API
Eric Laurentdc03c612011-04-01 10:59:41 -0700422 private static final int SCO_STATE_ACTIVE_INTERNAL = 3;
423 // SCO audio deactivation request waiting for headset service to connect
424 private static final int SCO_STATE_DEACTIVATE_REQ = 5;
425
Eric Laurent62ef7672010-11-24 10:58:32 -0800426 // SCO audio state is active due to an action in BT handsfree (either voice recognition or
427 // in call audio)
428 private static final int SCO_STATE_ACTIVE_EXTERNAL = 2;
Eric Laurentdc03c612011-04-01 10:59:41 -0700429 // Deactivation request for all SCO connections (initiated by audio mode change)
430 // waiting for headset service to connect
431 private static final int SCO_STATE_DEACTIVATE_EXT_REQ = 4;
432
Eric Laurentc18c9132013-04-12 17:24:56 -0700433 // Indicates the mode used for SCO audio connection. The mode is virtual call if the request
434 // originated from an app targeting an API version before JB MR2 and raw audio after that.
435 private int mScoAudioMode;
Liejun Taof4e51d82014-07-16 11:18:29 -0700436 // SCO audio mode is undefined
437 private static final int SCO_MODE_UNDEFINED = -1;
Eric Laurentc18c9132013-04-12 17:24:56 -0700438 // SCO audio mode is virtual voice call (BluetoothHeadset.startScoUsingVirtualVoiceCall())
439 private static final int SCO_MODE_VIRTUAL_CALL = 0;
440 // SCO audio mode is raw audio (BluetoothHeadset.connectAudio())
441 private static final int SCO_MODE_RAW = 1;
Liejun Taof4e51d82014-07-16 11:18:29 -0700442 // SCO audio mode is Voice Recognition (BluetoothHeadset.startVoiceRecognition())
443 private static final int SCO_MODE_VR = 2;
444
445 private static final int SCO_MODE_MAX = 2;
Eric Laurentc18c9132013-04-12 17:24:56 -0700446
Eric Laurentdc03c612011-04-01 10:59:41 -0700447 // Current connection state indicated by bluetooth headset
448 private int mScoConnectionState;
Eric Laurent62ef7672010-11-24 10:58:32 -0800449
Eric Laurenta60e2122010-12-28 16:49:07 -0800450 // true if boot sequence has been completed
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700451 private boolean mSystemReady;
Eric Laurenta60e2122010-12-28 16:49:07 -0800452 // listener for SoundPool sample load completion indication
453 private SoundPoolCallback mSoundPoolCallBack;
454 // thread for SoundPool listener
455 private SoundPoolListenerThread mSoundPoolListenerThread;
456 // message looper for SoundPool listener
457 private Looper mSoundPoolLooper = null;
Jean-Michel Trivic55b3932012-06-05 11:57:59 -0700458 // volume applied to sound played with playSoundEffect()
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -0700459 private static int sSoundEffectVolumeDb;
Eric Laurent25101b02011-02-02 09:33:30 -0800460 // previous volume adjustment direction received by checkForRingerModeChange()
461 private int mPrevVolDirection = AudioManager.ADJUST_SAME;
Amith Yamasani6243edd2011-12-05 19:58:48 -0800462 // Keyguard manager proxy
463 private KeyguardManager mKeyguardManager;
Eric Laurent45c90ce2012-04-24 18:44:22 -0700464 // mVolumeControlStream is set by VolumePanel to temporarily force the stream type which volume
465 // is controlled by Vol keys.
466 private int mVolumeControlStream = -1;
467 private final Object mForceControlStreamLock = new Object();
468 // VolumePanel is currently the only client of forceVolumeControlStream() and runs in system
469 // server process so in theory it is not necessary to monitor the client death.
470 // However it is good to be ready for future evolutions.
471 private ForceControlStreamClient mForceControlStreamClient = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700472 // Used to play ringtones outside system_server
473 private volatile IRingtonePlayer mRingtonePlayer;
Eric Laurent9bc8358d2011-11-18 16:43:31 -0800474
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700475 private int mDeviceOrientation = Configuration.ORIENTATION_UNDEFINED;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700476 private int mDeviceRotation = Surface.ROTATION_0;
Jean-Michel Trivif26f0172012-04-25 16:23:20 -0700477
Eric Laurent78472112012-05-21 08:57:21 -0700478 // Request to override default use of A2DP for media.
479 private boolean mBluetoothA2dpEnabled;
480 private final Object mBluetoothA2dpEnabledLock = new Object();
481
Dianne Hackborn632ca412012-06-14 19:34:10 -0700482 // Monitoring of audio routes. Protected by mCurAudioRoutes.
483 final AudioRoutesInfo mCurAudioRoutes = new AudioRoutesInfo();
484 final RemoteCallbackList<IAudioRoutesObserver> mRoutesObservers
485 = new RemoteCallbackList<IAudioRoutesObserver>();
486
Eric Laurent4bbcc652012-09-24 14:26:30 -0700487 // Devices for which the volume is fixed and VolumePanel slider should be disabled
Eric Laurent212532b2014-07-21 15:43:18 -0700488 int mFixedVolumeDevices = AudioSystem.DEVICE_OUT_HDMI |
Eric Laurent4bbcc652012-09-24 14:26:30 -0700489 AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET |
Eric Laurent212532b2014-07-21 15:43:18 -0700490 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET |
491 AudioSystem.DEVICE_OUT_HDMI_ARC |
492 AudioSystem.DEVICE_OUT_SPDIF |
493 AudioSystem.DEVICE_OUT_AUX_LINE;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -0700494 int mFullVolumeDevices = 0;
Eric Laurent4bbcc652012-09-24 14:26:30 -0700495
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700496 // TODO merge orientation and rotation
Eric Laurentd640bd32012-09-28 18:01:48 -0700497 private final boolean mMonitorOrientation;
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -0700498 private final boolean mMonitorRotation;
Eric Laurentd640bd32012-09-28 18:01:48 -0700499
Eric Laurent7ee1e4f2012-10-26 18:11:21 -0700500 private boolean mDockAudioMediaEnabled = true;
501
Eric Laurent08ed1b92012-11-05 14:54:12 -0800502 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
503
Eric Laurentfde16d52012-12-03 14:42:39 -0800504 // Used when safe volume warning message display is requested by setStreamVolume(). In this
505 // case, the new requested volume, stream type and device are stored in mPendingVolumeCommand
506 // and used later when/if disableSafeMediaVolume() is called.
507 private StreamVolumeCommand mPendingVolumeCommand;
508
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700509 private PowerManager.WakeLock mAudioEventWakeLock;
510
511 private final MediaFocusControl mMediaFocusControl;
512
John Du5a0cf7a2013-07-19 11:30:34 -0700513 // Reference to BluetoothA2dp to query for AbsoluteVolume.
514 private BluetoothA2dp mA2dp;
seunghwan.hong4fe77952014-10-29 17:43:20 +0900515 // lock always taken synchronized on mConnectedDevices
John Du5a0cf7a2013-07-19 11:30:34 -0700516 private final Object mA2dpAvrcpLock = new Object();
517 // If absolute volume is supported in AVRCP device
518 private boolean mAvrcpAbsVolSupported = false;
519
Jon Eklund318f0fe2014-01-23 17:53:48 -0600520 private AudioOrientationEventListener mOrientationListener;
521
Eric Laurentadbe8bf2014-11-03 18:26:32 -0800522 private static Long mLastDeviceConnectMsgTime = new Long(0);
523
John Spurlock661f2cf2014-11-17 10:29:10 -0500524 private AudioManagerInternal.RingerModeDelegate mRingerModeDelegate;
525
Paul McLean10804eb2015-01-28 11:16:35 -0800526 // Intent "extra" data keys.
527 public static final String CONNECT_INTENT_KEY_PORT_NAME = "portName";
528 public static final String CONNECT_INTENT_KEY_STATE = "state";
529 public static final String CONNECT_INTENT_KEY_ADDRESS = "address";
530 public static final String CONNECT_INTENT_KEY_HAS_PLAYBACK = "hasPlayback";
531 public static final String CONNECT_INTENT_KEY_HAS_CAPTURE = "hasCapture";
532 public static final String CONNECT_INTENT_KEY_HAS_MIDI = "hasMIDI";
533 public static final String CONNECT_INTENT_KEY_DEVICE_CLASS = "class";
534
535 // Defines the format for the connection "address" for ALSA devices
536 public static String makeAlsaAddressString(int card, int device) {
537 return "card=" + card + ";device=" + device + ";";
538 }
539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 ///////////////////////////////////////////////////////////////////////////
541 // Construction
542 ///////////////////////////////////////////////////////////////////////////
543
544 /** @hide */
545 public AudioService(Context context) {
546 mContext = context;
547 mContentResolver = context.getContentResolver();
Dianne Hackbornba50b97c2013-04-30 15:04:46 -0700548 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
Eric Laurent212532b2014-07-21 15:43:18 -0700549
John Spurlock61560172015-02-06 19:46:04 -0500550 mPlatformType = AudioSystem.getPlatformType(context);
Jared Suttles59820132009-08-13 21:50:52 -0500551
Jean-Michel Trivic6802222012-04-30 11:15:03 -0700552 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700553 mAudioEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleAudioEvent");
Jean-Michel Trivic6802222012-04-30 11:15:03 -0700554
Eric Laurentbffc3d12012-05-07 17:43:49 -0700555 Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
556 mHasVibrator = vibrator == null ? false : vibrator.hasVibrator();
557
Jared Suttles59820132009-08-13 21:50:52 -0500558 // Intialized volume
Eric Laurent91377de2014-10-10 15:24:04 -0700559 int maxVolume = SystemProperties.getInt("ro.config.vc_call_vol_steps",
560 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
561 if (maxVolume != MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]) {
562 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = maxVolume;
John Spurlock61560172015-02-06 19:46:04 -0500563 AudioSystem.DEFAULT_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = (maxVolume * 3) / 4;
Eric Laurent91377de2014-10-10 15:24:04 -0700564 }
565 maxVolume = SystemProperties.getInt("ro.config.media_vol_steps",
566 MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
567 if (maxVolume != MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]) {
568 MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC] = maxVolume;
John Spurlock61560172015-02-06 19:46:04 -0500569 AudioSystem.DEFAULT_STREAM_VOLUME[AudioSystem.STREAM_MUSIC] = (maxVolume * 3) / 4;
Eric Laurent91377de2014-10-10 15:24:04 -0700570 }
Jared Suttles59820132009-08-13 21:50:52 -0500571
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -0700572 sSoundEffectVolumeDb = context.getResources().getInteger(
Jean-Michel Trivic55b3932012-06-05 11:57:59 -0700573 com.android.internal.R.integer.config_soundEffectVolumeDb);
Eric Laurent25101b02011-02-02 09:33:30 -0800574
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700575 mForcedUseForComm = AudioSystem.FORCE_NONE;
Eric Laurentdd45d012012-10-08 09:04:34 -0700576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 createAudioSystemThread();
Eric Laurentdd45d012012-10-08 09:04:34 -0700578
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700579 mMediaFocusControl = new MediaFocusControl(mAudioHandler.getLooper(),
John Spurlock3346a802014-05-20 16:25:37 -0400580 mContext, mVolumeController, this);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -0700581
Eric Laurentdfb881f2013-07-18 14:41:39 -0700582 AudioSystem.setErrorCallback(mAudioSystemCallback);
583
John Spurlock5e783732015-02-19 10:28:59 -0500584 boolean cameraSoundForced = readCameraSoundForced();
Eric Laurentdd45d012012-10-08 09:04:34 -0700585 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
John Spurlock3ce37252015-02-17 13:20:45 -05001001 if (isMuteAdjust && !isStreamAffectedByMute(streamType)) {
1002 return;
1003 }
1004
Eric Laurent96a33d12011-11-08 10:31:57 -08001005 // use stream type alias here so that streams with same alias have the same behavior,
1006 // including with regard to silent mode control (e.g the use of STREAM_RING below and in
1007 // checkForRingerModeChange() in place of STREAM_RING or STREAM_NOTIFICATION)
Eric Laurent6d517662012-04-23 18:42:39 -07001008 int streamTypeAlias = mStreamVolumeAlias[streamType];
RoboErik4197cb62015-01-21 15:45:32 -08001009
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);
RoboErik4197cb62015-01-21 15:45:32 -08001109 }
1110 }
1111 } else if ((direction == AudioManager.ADJUST_RAISE) &&
Eric Laurent42b041e2013-03-29 11:36:03 -07001112 !checkSafeMediaVolume(streamTypeAlias, aliasIndex + step, device)) {
RoboErik4197cb62015-01-21 15:45:32 -08001113 Log.e(TAG, "adjustStreamVolume() safe volume index = " + oldIndex);
John Spurlock3346a802014-05-20 16:25:37 -04001114 mVolumeController.postDisplaySafeVolumeWarning(flags);
RoboErik4197cb62015-01-21 15:45:32 -08001115 } else if (streamState.adjustIndex(direction * step, device) || streamState.mIsMuted) {
1116 // Post message to set system volume (it in turn will post a
1117 // message to persist).
1118 if (streamState.mIsMuted) {
1119 // Unmute the stream if it was previously muted
RoboErik5452e252015-02-06 15:33:53 -08001120 if (direction == AudioManager.ADJUST_RAISE) {
1121 // unmute immediately for volume up
1122 streamState.mute(false);
1123 } else if (direction == AudioManager.ADJUST_LOWER) {
1124 sendMsg(mAudioHandler, MSG_UNMUTE_STREAM, SENDMSG_QUEUE,
1125 streamTypeAlias, flags, null, UNMUTE_STREAM_DELAY);
1126 }
RoboErik4197cb62015-01-21 15:45:32 -08001127 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001128 sendMsg(mAudioHandler,
1129 MSG_SET_DEVICE_VOLUME,
1130 SENDMSG_QUEUE,
1131 device,
1132 0,
1133 streamState,
1134 0);
Eric Laurent4bbcc652012-09-24 14:26:30 -07001135 }
Jungshik Jang41d97462014-06-30 22:26:29 +09001136
RoboErik4197cb62015-01-21 15:45:32 -08001137 // Check if volume update should be sent to Hdmi system audio.
Jungshik Jang41d97462014-06-30 22:26:29 +09001138 int newIndex = mStreamStates[streamType].getIndex(device);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001139 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1140 setSystemAudioVolume(oldIndex, newIndex, getStreamMaxVolume(streamType), flags);
1141 }
Eric Laurent212532b2014-07-21 15:43:18 -07001142 if (mHdmiManager != null) {
1143 synchronized (mHdmiManager) {
Eric Laurent212532b2014-07-21 15:43:18 -07001144 // mHdmiCecSink true => mHdmiPlaybackClient != null
1145 if (mHdmiCecSink &&
1146 streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1147 oldIndex != newIndex) {
1148 synchronized (mHdmiPlaybackClient) {
1149 int keyCode = (direction == -1) ? KeyEvent.KEYCODE_VOLUME_DOWN :
RoboErik4197cb62015-01-21 15:45:32 -08001150 KeyEvent.KEYCODE_VOLUME_UP;
Eric Laurent212532b2014-07-21 15:43:18 -07001151 mHdmiPlaybackClient.sendKeyEvent(keyCode, true);
1152 mHdmiPlaybackClient.sendKeyEvent(keyCode, false);
1153 }
Jungshik Jang41d97462014-06-30 22:26:29 +09001154 }
1155 }
1156 }
Eric Laurent4bbcc652012-09-24 14:26:30 -07001157 }
Eric Laurent42b041e2013-03-29 11:36:03 -07001158 int index = mStreamStates[streamType].getIndex(device);
Eric Laurent25101b02011-02-02 09:33:30 -08001159 sendVolumeUpdate(streamType, oldIndex, index, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161
RoboErik5452e252015-02-06 15:33:53 -08001162 // Called after a delay when volume down is pressed while muted
1163 private void onUnmuteStream(int stream, int flags) {
1164 VolumeStreamState streamState = mStreamStates[stream];
1165 streamState.mute(false);
1166
1167 final int device = getDeviceForStream(stream);
1168 final int index = mStreamStates[stream].getIndex(device);
1169 sendVolumeUpdate(stream, index, index, flags);
1170 }
1171
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001172 private void setSystemAudioVolume(int oldVolume, int newVolume, int maxVolume, int flags) {
1173 if (mHdmiManager == null
1174 || mHdmiTvClient == null
1175 || oldVolume == newVolume
1176 || (flags & AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME) != 0) return;
1177
1178 // Sets the audio volume of AVR when we are in system audio mode. The new volume info
1179 // is tranformed to HDMI-CEC commands and passed through CEC bus.
1180 synchronized (mHdmiManager) {
1181 if (!mHdmiSystemAudioSupported) return;
1182 synchronized (mHdmiTvClient) {
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001183 final long token = Binder.clearCallingIdentity();
1184 try {
Jinsuk Kim7a9ba422015-02-16 16:47:38 +09001185 mHdmiTvClient.setSystemAudioVolume(oldVolume, newVolume, maxVolume);
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001186 } finally {
1187 Binder.restoreCallingIdentity(token);
1188 }
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001189 }
1190 }
1191 }
1192
Dianne Hackborn961cae92013-03-20 14:59:43 -07001193 /** @see AudioManager#adjustMasterVolume(int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001194 public void adjustMasterVolume(int steps, int flags, String callingPackage) {
RoboErik519c7742014-11-18 10:59:09 -08001195 adjustMasterVolume(steps, flags, callingPackage, Binder.getCallingUid());
1196 }
1197
1198 public void adjustMasterVolume(int steps, int flags, String callingPackage, int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001199 if (mUseFixedVolume) {
1200 return;
1201 }
RoboErik4197cb62015-01-21 15:45:32 -08001202 if (isMuteAdjust(steps)) {
1203 setMasterMuteInternal(steps, flags, callingPackage, uid);
1204 return;
1205 }
Lei Zhang6c798972012-03-02 11:40:12 -08001206 ensureValidSteps(steps);
Mike Lockwood97606472012-02-09 11:24:10 -08001207 int volume = Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME);
1208 int delta = 0;
Lei Zhang6c798972012-03-02 11:40:12 -08001209 int numSteps = Math.abs(steps);
1210 int direction = steps > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER;
1211 for (int i = 0; i < numSteps; ++i) {
1212 delta = findVolumeDelta(direction, volume);
1213 volume += delta;
Mike Lockwoodcbdb49d2011-10-20 12:54:05 -04001214 }
RoboErik24b082f2012-02-24 14:21:16 -08001215
Lei Zhang6c798972012-03-02 11:40:12 -08001216 //Log.d(TAG, "adjustMasterVolume volume: " + volume + " steps: " + steps);
RoboErik519c7742014-11-18 10:59:09 -08001217 setMasterVolume(volume, flags, callingPackage, uid);
Mike Lockwoodcbdb49d2011-10-20 12:54:05 -04001218 }
1219
Eric Laurentfde16d52012-12-03 14:42:39 -08001220 // StreamVolumeCommand contains the information needed to defer the process of
1221 // setStreamVolume() in case the user has to acknowledge the safe volume warning message.
1222 class StreamVolumeCommand {
1223 public final int mStreamType;
1224 public final int mIndex;
1225 public final int mFlags;
1226 public final int mDevice;
Eric Laurent9ce379a2010-02-16 06:00:26 -08001227
Eric Laurentfde16d52012-12-03 14:42:39 -08001228 StreamVolumeCommand(int streamType, int index, int flags, int device) {
1229 mStreamType = streamType;
1230 mIndex = index;
1231 mFlags = flags;
1232 mDevice = device;
Eric Laurentb024c302011-10-14 17:19:27 -07001233 }
John Spurlock35134602014-07-24 18:10:48 -04001234
1235 @Override
1236 public String toString() {
1237 return new StringBuilder().append("{streamType=").append(mStreamType).append(",index=")
1238 .append(mIndex).append(",flags=").append(mFlags).append(",device=")
1239 .append(mDevice).append('}').toString();
1240 }
Eric Laurentfde16d52012-12-03 14:42:39 -08001241 };
Eric Laurent3ef75492012-11-28 12:12:23 -08001242
Eric Laurentfde16d52012-12-03 14:42:39 -08001243 private void onSetStreamVolume(int streamType, int index, int flags, int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07001244 setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, false);
Eric Laurent3ef75492012-11-28 12:12:23 -08001245 // setting volume on master stream type also controls silent mode
1246 if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
1247 (mStreamVolumeAlias[streamType] == getMasterStreamType())) {
1248 int newRingerMode;
1249 if (index == 0) {
1250 newRingerMode = mHasVibrator ? AudioManager.RINGER_MODE_VIBRATE
John Spurlock86005342014-05-23 11:58:00 -04001251 : VOLUME_SETS_RINGER_MODE_SILENT ? AudioManager.RINGER_MODE_SILENT
1252 : AudioManager.RINGER_MODE_NORMAL;
Eric Laurent3ef75492012-11-28 12:12:23 -08001253 } else {
1254 newRingerMode = AudioManager.RINGER_MODE_NORMAL;
1255 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001256 setRingerMode(newRingerMode, TAG + ".onSetStreamVolume", false /*external*/);
Eric Laurent3ef75492012-11-28 12:12:23 -08001257 }
Eric Laurentfde16d52012-12-03 14:42:39 -08001258 }
1259
1260 /** @see AudioManager#setStreamVolume(int, int, int) */
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001261 public void setStreamVolume(int streamType, int index, int flags, String callingPackage) {
RoboErik0dac35a2014-08-12 15:48:49 -07001262 setStreamVolume(streamType, index, flags, callingPackage, Binder.getCallingUid());
1263 }
1264
1265 private void setStreamVolume(int streamType, int index, int flags, String callingPackage,
1266 int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001267 if (mUseFixedVolume) {
1268 return;
1269 }
1270
Eric Laurentfde16d52012-12-03 14:42:39 -08001271 ensureValidStreamType(streamType);
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001272 int streamTypeAlias = mStreamVolumeAlias[streamType];
1273 VolumeStreamState streamState = mStreamStates[streamTypeAlias];
Eric Laurentfde16d52012-12-03 14:42:39 -08001274
1275 final int device = getDeviceForStream(streamType);
1276 int oldIndex;
1277
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001278 // skip a2dp absolute volume control request when the device
1279 // is not an a2dp device
1280 if ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) == 0 &&
1281 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) != 0) {
1282 return;
1283 }
1284
RoboErik0dac35a2014-08-12 15:48:49 -07001285 if (mAppOps.noteOp(STEAM_VOLUME_OPS[streamTypeAlias], uid, callingPackage)
1286 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001287 return;
1288 }
1289
Eric Laurentfde16d52012-12-03 14:42:39 -08001290 synchronized (mSafeMediaVolumeState) {
1291 // reset any pending volume command
1292 mPendingVolumeCommand = null;
1293
Eric Laurent42b041e2013-03-29 11:36:03 -07001294 oldIndex = streamState.getIndex(device);
Eric Laurentfde16d52012-12-03 14:42:39 -08001295
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001296 index = rescaleIndex(index * 10, streamType, streamTypeAlias);
Eric Laurentfde16d52012-12-03 14:42:39 -08001297
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001298 if (streamTypeAlias == AudioSystem.STREAM_MUSIC &&
1299 (device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
1300 (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) {
1301 synchronized (mA2dpAvrcpLock) {
1302 if (mA2dp != null && mAvrcpAbsVolSupported) {
Zhihai Xu2f4a2b12014-01-10 16:44:39 -08001303 mA2dp.setAvrcpAbsoluteVolume(index / 10);
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07001304 }
John Du5a0cf7a2013-07-19 11:30:34 -07001305 }
1306 }
1307
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001308 if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
1309 setSystemAudioVolume(oldIndex, index, getStreamMaxVolume(streamType), flags);
Jungshik Jang41d97462014-06-30 22:26:29 +09001310 }
1311
Eric Laurentfde16d52012-12-03 14:42:39 -08001312 flags &= ~AudioManager.FLAG_FIXED_VOLUME;
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001313 if ((streamTypeAlias == AudioSystem.STREAM_MUSIC) &&
Eric Laurentfde16d52012-12-03 14:42:39 -08001314 ((device & mFixedVolumeDevices) != 0)) {
1315 flags |= AudioManager.FLAG_FIXED_VOLUME;
1316
1317 // volume is either 0 or max allowed for fixed volume devices
1318 if (index != 0) {
1319 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE &&
1320 (device & mSafeMediaVolumeDevices) != 0) {
1321 index = mSafeMediaVolumeIndex;
1322 } else {
1323 index = streamState.getMaxIndex();
1324 }
1325 }
1326 }
1327
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001328 if (!checkSafeMediaVolume(streamTypeAlias, index, device)) {
John Spurlock3346a802014-05-20 16:25:37 -04001329 mVolumeController.postDisplaySafeVolumeWarning(flags);
Eric Laurentfde16d52012-12-03 14:42:39 -08001330 mPendingVolumeCommand = new StreamVolumeCommand(
1331 streamType, index, flags, device);
1332 } else {
1333 onSetStreamVolume(streamType, index, flags, device);
Eric Laurent42b041e2013-03-29 11:36:03 -07001334 index = mStreamStates[streamType].getIndex(device);
Eric Laurentfde16d52012-12-03 14:42:39 -08001335 }
1336 }
Eric Laurent25101b02011-02-02 09:33:30 -08001337 sendVolumeUpdate(streamType, oldIndex, index, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
1339
Eric Laurent45c90ce2012-04-24 18:44:22 -07001340 /** @see AudioManager#forceVolumeControlStream(int) */
1341 public void forceVolumeControlStream(int streamType, IBinder cb) {
1342 synchronized(mForceControlStreamLock) {
1343 mVolumeControlStream = streamType;
1344 if (mVolumeControlStream == -1) {
1345 if (mForceControlStreamClient != null) {
1346 mForceControlStreamClient.release();
1347 mForceControlStreamClient = null;
1348 }
1349 } else {
1350 mForceControlStreamClient = new ForceControlStreamClient(cb);
1351 }
1352 }
1353 }
1354
1355 private class ForceControlStreamClient implements IBinder.DeathRecipient {
1356 private IBinder mCb; // To be notified of client's death
1357
1358 ForceControlStreamClient(IBinder cb) {
1359 if (cb != null) {
1360 try {
1361 cb.linkToDeath(this, 0);
1362 } catch (RemoteException e) {
1363 // Client has died!
1364 Log.w(TAG, "ForceControlStreamClient() could not link to "+cb+" binder death");
1365 cb = null;
1366 }
1367 }
1368 mCb = cb;
1369 }
1370
1371 public void binderDied() {
1372 synchronized(mForceControlStreamLock) {
1373 Log.w(TAG, "SCO client died");
1374 if (mForceControlStreamClient != this) {
1375 Log.w(TAG, "unregistered control stream client died");
1376 } else {
1377 mForceControlStreamClient = null;
1378 mVolumeControlStream = -1;
1379 }
1380 }
1381 }
1382
1383 public void release() {
1384 if (mCb != null) {
1385 mCb.unlinkToDeath(this, 0);
1386 mCb = null;
1387 }
1388 }
1389 }
1390
Lei Zhang6c798972012-03-02 11:40:12 -08001391 private int findVolumeDelta(int direction, int volume) {
1392 int delta = 0;
1393 if (direction == AudioManager.ADJUST_RAISE) {
1394 if (volume == MAX_MASTER_VOLUME) {
1395 return 0;
1396 }
1397 // This is the default value if we make it to the end
1398 delta = mMasterVolumeRamp[1];
1399 // If we're raising the volume move down the ramp array until we
1400 // find the volume we're above and use that groups delta.
1401 for (int i = mMasterVolumeRamp.length - 1; i > 1; i -= 2) {
1402 if (volume >= mMasterVolumeRamp[i - 1]) {
1403 delta = mMasterVolumeRamp[i];
1404 break;
1405 }
1406 }
1407 } else if (direction == AudioManager.ADJUST_LOWER){
1408 if (volume == 0) {
1409 return 0;
1410 }
1411 int length = mMasterVolumeRamp.length;
1412 // This is the default value if we make it to the end
1413 delta = -mMasterVolumeRamp[length - 1];
1414 // If we're lowering the volume move up the ramp array until we
1415 // find the volume we're below and use the group below it's delta
1416 for (int i = 2; i < length; i += 2) {
1417 if (volume <= mMasterVolumeRamp[i]) {
1418 delta = -mMasterVolumeRamp[i - 1];
1419 break;
1420 }
1421 }
1422 }
1423 return delta;
1424 }
1425
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001426 private void sendBroadcastToAll(Intent intent) {
Christopher Tate267603f2015-01-20 14:21:21 -08001427 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001428 final long ident = Binder.clearCallingIdentity();
1429 try {
1430 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1431 } finally {
1432 Binder.restoreCallingIdentity(ident);
1433 }
1434 }
1435
1436 private void sendStickyBroadcastToAll(Intent intent) {
1437 final long ident = Binder.clearCallingIdentity();
1438 try {
1439 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1440 } finally {
1441 Binder.restoreCallingIdentity(ident);
1442 }
1443 }
1444
Eric Laurent25101b02011-02-02 09:33:30 -08001445 // UI update and Broadcast Intent
1446 private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) {
Eric Laurent212532b2014-07-21 15:43:18 -07001447 if (!isPlatformVoice() && (streamType == AudioSystem.STREAM_RING)) {
Eric Laurent25101b02011-02-02 09:33:30 -08001448 streamType = AudioSystem.STREAM_NOTIFICATION;
1449 }
1450
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001451 if (streamType == AudioSystem.STREAM_MUSIC) {
1452 flags = updateFlagsForSystemAudio(flags);
Jungshik Jang1a6be6e2014-09-16 11:04:54 +09001453 }
John Spurlock3346a802014-05-20 16:25:37 -04001454 mVolumeController.postVolumeChanged(streamType, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
1456
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001457 // If Hdmi-CEC system audio mode is on, we show volume bar only when TV
1458 // receives volume notification from Audio Receiver.
1459 private int updateFlagsForSystemAudio(int flags) {
1460 if (mHdmiTvClient != null) {
1461 synchronized (mHdmiTvClient) {
1462 if (mHdmiSystemAudioSupported &&
1463 ((flags & AudioManager.FLAG_HDMI_SYSTEM_AUDIO_VOLUME) == 0)) {
1464 flags &= ~AudioManager.FLAG_SHOW_UI;
1465 }
1466 }
1467 }
1468 return flags;
1469 }
1470
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001471 // UI update and Broadcast Intent
1472 private void sendMasterVolumeUpdate(int flags, int oldVolume, int newVolume) {
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001473 mVolumeController.postMasterVolumeChanged(updateFlagsForSystemAudio(flags));
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001474
1475 Intent intent = new Intent(AudioManager.MASTER_VOLUME_CHANGED_ACTION);
1476 intent.putExtra(AudioManager.EXTRA_PREV_MASTER_VOLUME_VALUE, oldVolume);
1477 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_VALUE, newVolume);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001478 sendBroadcastToAll(intent);
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001479 }
1480
1481 // UI update and Broadcast Intent
1482 private void sendMasterMuteUpdate(boolean muted, int flags) {
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001483 mVolumeController.postMasterMuteChanged(updateFlagsForSystemAudio(flags));
Justin Koh57978ed2012-04-03 17:37:58 -07001484 broadcastMasterMuteStatus(muted);
1485 }
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001486
Justin Koh57978ed2012-04-03 17:37:58 -07001487 private void broadcastMasterMuteStatus(boolean muted) {
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001488 Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
1489 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, muted);
Justin Koh57978ed2012-04-03 17:37:58 -07001490 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1491 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001492 sendStickyBroadcastToAll(intent);
Mike Lockwood0dc37cc2011-12-01 16:14:19 -05001493 }
1494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 * Sets the stream state's index, and posts a message to set system volume.
1497 * This will not call out to the UI. Assumes a valid stream type.
1498 *
1499 * @param streamType Type of the stream
1500 * @param index Desired volume index of the stream
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001501 * @param device the device whose volume must be changed
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 * @param force If true, set the volume even if the desired volume is same
1503 * as the current volume.
1504 */
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001505 private void setStreamVolumeInt(int streamType,
1506 int index,
1507 int device,
Eric Laurent42b041e2013-03-29 11:36:03 -07001508 boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurent5b4e6542010-03-19 20:02:21 -07001510
Eric Laurent42b041e2013-03-29 11:36:03 -07001511 if (streamState.setIndex(index, device) || force) {
1512 // Post message to set system volume (it in turn will post a message
1513 // to persist).
1514 sendMsg(mAudioHandler,
1515 MSG_SET_DEVICE_VOLUME,
1516 SENDMSG_QUEUE,
1517 device,
1518 0,
1519 streamState,
1520 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522 }
1523
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001524 private void setSystemAudioMute(boolean state) {
1525 if (mHdmiManager == null || mHdmiTvClient == null) return;
1526 synchronized (mHdmiManager) {
Jinsuk Kim48cbf292014-12-13 02:16:28 +09001527 if (!mHdmiSystemAudioSupported) return;
1528 synchronized (mHdmiTvClient) {
1529 final long token = Binder.clearCallingIdentity();
1530 try {
1531 mHdmiTvClient.setSystemAudioMute(state);
1532 } finally {
1533 Binder.restoreCallingIdentity(token);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001534 }
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001535 }
1536 }
1537 }
1538
Eric Laurent25101b02011-02-02 09:33:30 -08001539 /** get stream mute state. */
1540 public boolean isStreamMute(int streamType) {
RoboErik7c82ced2014-12-04 17:39:08 -08001541 if (streamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1542 streamType = getActiveStreamType(streamType);
1543 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001544 synchronized (VolumeStreamState.class) {
RoboErik4197cb62015-01-21 15:45:32 -08001545 return mStreamStates[streamType].mIsMuted;
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001546 }
Eric Laurent25101b02011-02-02 09:33:30 -08001547 }
1548
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07001549 private class RmtSbmxFullVolDeathHandler implements IBinder.DeathRecipient {
1550 private IBinder mICallback; // To be notified of client's death
1551
1552 RmtSbmxFullVolDeathHandler(IBinder cb) {
1553 mICallback = cb;
1554 try {
1555 cb.linkToDeath(this, 0/*flags*/);
1556 } catch (RemoteException e) {
1557 Log.e(TAG, "can't link to death", e);
1558 }
1559 }
1560
1561 boolean isHandlerFor(IBinder cb) {
1562 return mICallback.equals(cb);
1563 }
1564
1565 void forget() {
1566 try {
1567 mICallback.unlinkToDeath(this, 0/*flags*/);
1568 } catch (NoSuchElementException e) {
1569 Log.e(TAG, "error unlinking to death", e);
1570 }
1571 }
1572
1573 public void binderDied() {
1574 Log.w(TAG, "Recorder with remote submix at full volume died " + mICallback);
1575 forceRemoteSubmixFullVolume(false, mICallback);
1576 }
1577 }
1578
1579 /**
1580 * call must be synchronized on mRmtSbmxFullVolDeathHandlers
1581 * @return true if there is a registered death handler, false otherwise */
1582 private boolean discardRmtSbmxFullVolDeathHandlerFor(IBinder cb) {
1583 Iterator<RmtSbmxFullVolDeathHandler> it = mRmtSbmxFullVolDeathHandlers.iterator();
1584 while (it.hasNext()) {
1585 final RmtSbmxFullVolDeathHandler handler = it.next();
1586 if (handler.isHandlerFor(cb)) {
1587 handler.forget();
1588 mRmtSbmxFullVolDeathHandlers.remove(handler);
1589 return true;
1590 }
1591 }
1592 return false;
1593 }
1594
1595 /** call synchronized on mRmtSbmxFullVolDeathHandlers */
1596 private boolean hasRmtSbmxFullVolDeathHandlerFor(IBinder cb) {
1597 Iterator<RmtSbmxFullVolDeathHandler> it = mRmtSbmxFullVolDeathHandlers.iterator();
1598 while (it.hasNext()) {
1599 if (it.next().isHandlerFor(cb)) {
1600 return true;
1601 }
1602 }
1603 return false;
1604 }
1605
1606 private int mRmtSbmxFullVolRefCount = 0;
1607 private ArrayList<RmtSbmxFullVolDeathHandler> mRmtSbmxFullVolDeathHandlers =
1608 new ArrayList<RmtSbmxFullVolDeathHandler>();
1609
1610 public void forceRemoteSubmixFullVolume(boolean startForcing, IBinder cb) {
1611 if (cb == null) {
1612 return;
1613 }
1614 if ((PackageManager.PERMISSION_GRANTED != mContext.checkCallingOrSelfPermission(
1615 android.Manifest.permission.CAPTURE_AUDIO_OUTPUT))) {
1616 Log.w(TAG, "Trying to call forceRemoteSubmixFullVolume() without CAPTURE_AUDIO_OUTPUT");
1617 return;
1618 }
1619 synchronized(mRmtSbmxFullVolDeathHandlers) {
1620 boolean applyRequired = false;
1621 if (startForcing) {
1622 if (!hasRmtSbmxFullVolDeathHandlerFor(cb)) {
1623 mRmtSbmxFullVolDeathHandlers.add(new RmtSbmxFullVolDeathHandler(cb));
1624 if (mRmtSbmxFullVolRefCount == 0) {
1625 mFullVolumeDevices |= AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1626 mFixedVolumeDevices |= AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1627 applyRequired = true;
1628 }
1629 mRmtSbmxFullVolRefCount++;
1630 }
1631 } else {
1632 if (discardRmtSbmxFullVolDeathHandlerFor(cb) && (mRmtSbmxFullVolRefCount > 0)) {
1633 mRmtSbmxFullVolRefCount--;
1634 if (mRmtSbmxFullVolRefCount == 0) {
1635 mFullVolumeDevices &= ~AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1636 mFixedVolumeDevices &= ~AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
1637 applyRequired = true;
1638 }
1639 }
1640 }
1641 if (applyRequired) {
1642 // Assumes only STREAM_MUSIC going through DEVICE_OUT_REMOTE_SUBMIX
1643 checkAllFixedVolumeDevices(AudioSystem.STREAM_MUSIC);
1644 mStreamStates[AudioSystem.STREAM_MUSIC].applyAllVolumes();
1645 }
1646 }
1647 }
1648
RoboErik4197cb62015-01-21 15:45:32 -08001649 private void setMasterMuteInternal(int adjust, int flags, String callingPackage, int uid) {
RoboErik7c82ced2014-12-04 17:39:08 -08001650 if (mAppOps.noteOp(AppOpsManager.OP_AUDIO_MASTER_VOLUME, uid, callingPackage)
1651 != AppOpsManager.MODE_ALLOWED) {
Julia Reynolds4a21b252014-06-04 11:11:43 -04001652 return;
1653 }
RoboErik4197cb62015-01-21 15:45:32 -08001654 boolean state;
1655 if (adjust == AudioManager.ADJUST_TOGGLE_MUTE) {
1656 state = !AudioSystem.getMasterMute();
1657 } else {
1658 state = adjust == AudioManager.ADJUST_MUTE;
1659 }
Jason Simmons1ce5b262012-02-02 13:00:17 -08001660 if (state != AudioSystem.getMasterMute()) {
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001661 setSystemAudioMute(state);
Jason Simmons1ce5b262012-02-02 13:00:17 -08001662 AudioSystem.setMasterMute(state);
Justin Koh57978ed2012-04-03 17:37:58 -07001663 // Post a persist master volume msg
Justin Koh75cf9e12012-04-04 15:27:37 -07001664 sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME_MUTE, SENDMSG_REPLACE, state ? 1
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001665 : 0, UserHandle.getCallingUserId(), null, PERSIST_DELAY);
Justin Koh0273af52012-04-04 18:29:50 -07001666 sendMasterMuteUpdate(state, flags);
RoboErik7c82ced2014-12-04 17:39:08 -08001667
1668 Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
1669 intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, state);
1670 sendBroadcastToAll(intent);
Jason Simmons1ce5b262012-02-02 13:00:17 -08001671 }
Mike Lockwoodce952c82011-11-14 10:47:42 -08001672 }
1673
1674 /** get master mute state. */
1675 public boolean isMasterMute() {
Mike Lockwood3194ea92011-12-07 11:47:31 -08001676 return AudioSystem.getMasterMute();
Mike Lockwoodce952c82011-11-14 10:47:42 -08001677 }
1678
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07001679 protected static int getMaxStreamVolume(int streamType) {
1680 return MAX_STREAM_VOLUME[streamType];
1681 }
1682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 /** @see AudioManager#getStreamVolume(int) */
1684 public int getStreamVolume(int streamType) {
1685 ensureValidStreamType(streamType);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001686 int device = getDeviceForStream(streamType);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001687 synchronized (VolumeStreamState.class) {
1688 int index = mStreamStates[streamType].getIndex(device);
Eric Laurent4bbcc652012-09-24 14:26:30 -07001689
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001690 // by convention getStreamVolume() returns 0 when a stream is muted.
RoboErik4197cb62015-01-21 15:45:32 -08001691 if (mStreamStates[streamType].mIsMuted) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07001692 index = 0;
1693 }
1694 if (index != 0 && (mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) &&
1695 (device & mFixedVolumeDevices) != 0) {
1696 index = mStreamStates[streamType].getMaxIndex();
1697 }
1698 return (index + 5) / 10;
Eric Laurent42b041e2013-03-29 11:36:03 -07001699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701
RoboErik519c7742014-11-18 10:59:09 -08001702 @Override
Mike Lockwood47676902011-11-08 10:31:21 -08001703 public int getMasterVolume() {
Mike Lockwoodce952c82011-11-14 10:47:42 -08001704 if (isMasterMute()) return 0;
1705 return getLastAudibleMasterVolume();
Mike Lockwood8dc1dab2011-10-27 09:52:41 -04001706 }
1707
RoboErik519c7742014-11-18 10:59:09 -08001708 @Override
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001709 public void setMasterVolume(int volume, int flags, String callingPackage) {
RoboErik519c7742014-11-18 10:59:09 -08001710 setMasterVolume(volume, flags, callingPackage, Binder.getCallingUid());
1711 }
1712
1713 public void setMasterVolume(int volume, int flags, String callingPackage, int uid) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001714 if (mUseFixedVolume) {
1715 return;
1716 }
1717
RoboErik519c7742014-11-18 10:59:09 -08001718 if (mAppOps.noteOp(AppOpsManager.OP_AUDIO_MASTER_VOLUME, uid, callingPackage)
1719 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornba50b97c2013-04-30 15:04:46 -07001720 return;
1721 }
1722
Mike Lockwood97606472012-02-09 11:24:10 -08001723 if (volume < 0) {
1724 volume = 0;
1725 } else if (volume > MAX_MASTER_VOLUME) {
1726 volume = MAX_MASTER_VOLUME;
1727 }
Mike Lockwood5c55a052011-12-15 17:21:44 -05001728 doSetMasterVolume((float)volume / MAX_MASTER_VOLUME, flags);
1729 }
1730
1731 private void doSetMasterVolume(float volume, int flags) {
1732 // don't allow changing master volume when muted
1733 if (!AudioSystem.getMasterMute()) {
1734 int oldVolume = getMasterVolume();
1735 AudioSystem.setMasterVolume(volume);
1736
1737 int newVolume = getMasterVolume();
1738 if (newVolume != oldVolume) {
1739 // Post a persist master volume msg
1740 sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME, SENDMSG_REPLACE,
1741 Math.round(volume * (float)1000.0), 0, null, PERSIST_DELAY);
Jinsuk Kim336cdb42014-11-29 06:27:00 +09001742 setSystemAudioVolume(oldVolume, newVolume, getMasterMaxVolume(), flags);
Mike Lockwood5c55a052011-12-15 17:21:44 -05001743 }
Justin Koh3caba512012-04-02 15:32:18 -07001744 // Send the volume update regardless whether there was a change.
1745 sendMasterVolumeUpdate(flags, oldVolume, newVolume);
Mike Lockwood5c55a052011-12-15 17:21:44 -05001746 }
Mike Lockwood8dc1dab2011-10-27 09:52:41 -04001747 }
1748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 /** @see AudioManager#getStreamMaxVolume(int) */
1750 public int getStreamMaxVolume(int streamType) {
1751 ensureValidStreamType(streamType);
Eric Laurenta553c252009-07-17 12:17:14 -07001752 return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
1754
Mike Lockwood47676902011-11-08 10:31:21 -08001755 public int getMasterMaxVolume() {
1756 return MAX_MASTER_VOLUME;
1757 }
Eric Laurent25101b02011-02-02 09:33:30 -08001758
1759 /** Get last audible volume before stream was muted. */
1760 public int getLastAudibleStreamVolume(int streamType) {
1761 ensureValidStreamType(streamType);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001762 int device = getDeviceForStream(streamType);
Eric Laurent42b041e2013-03-29 11:36:03 -07001763 return (mStreamStates[streamType].getIndex(device) + 5) / 10;
Eric Laurent25101b02011-02-02 09:33:30 -08001764 }
1765
Mike Lockwoodce952c82011-11-14 10:47:42 -08001766 /** Get last audible master volume before it was muted. */
1767 public int getLastAudibleMasterVolume() {
1768 return Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME);
1769 }
1770
Dianne Hackborn961cae92013-03-20 14:59:43 -07001771 /** @see AudioManager#getMasterStreamType() */
Eric Laurent6d517662012-04-23 18:42:39 -07001772 public int getMasterStreamType() {
John Spurlock4f0f1202014-08-05 13:28:33 -04001773 return mStreamVolumeAlias[AudioSystem.STREAM_SYSTEM];
Eric Laurent6d517662012-04-23 18:42:39 -07001774 }
1775
Emily Bernier22c921a2014-05-28 11:01:32 -04001776 /** @see AudioManager#setMicrophoneMute(boolean) */
1777 public void setMicrophoneMute(boolean on, String callingPackage) {
1778 if (mAppOps.noteOp(AppOpsManager.OP_MUTE_MICROPHONE, Binder.getCallingUid(),
1779 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1780 return;
1781 }
Jean-Michel Trivi4a4fea02014-08-29 18:14:09 -07001782 if (!checkAudioSettingsPermission("setMicrophoneMute()")) {
1783 return;
1784 }
Emily Bernier22c921a2014-05-28 11:01:32 -04001785
1786 AudioSystem.muteMicrophone(on);
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001787 // Post a persist microphone msg.
1788 sendMsg(mAudioHandler, MSG_PERSIST_MICROPHONE_MUTE, SENDMSG_REPLACE, on ? 1
1789 : 0, UserHandle.getCallingUserId(), null, PERSIST_DELAY);
Emily Bernier22c921a2014-05-28 11:01:32 -04001790 }
1791
John Spurlock661f2cf2014-11-17 10:29:10 -05001792 @Override
1793 public int getRingerModeExternal() {
1794 synchronized(mSettingsLock) {
1795 return mRingerModeExternal;
1796 }
1797 }
1798
1799 @Override
1800 public int getRingerModeInternal() {
Glenn Kastenba195eb2011-12-13 09:30:40 -08001801 synchronized(mSettingsLock) {
1802 return mRingerMode;
1803 }
1804 }
1805
1806 private void ensureValidRingerMode(int ringerMode) {
John Spurlock97559372014-10-24 16:27:36 -04001807 if (!isValidRingerMode(ringerMode)) {
Glenn Kastenba195eb2011-12-13 09:30:40 -08001808 throw new IllegalArgumentException("Bad ringer mode " + ringerMode);
1809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
1811
John Spurlock97559372014-10-24 16:27:36 -04001812 /** @see AudioManager#isValidRingerMode(int) */
1813 public boolean isValidRingerMode(int ringerMode) {
1814 return ringerMode >= 0 && ringerMode <= AudioManager.RINGER_MODE_MAX;
1815 }
1816
John Spurlock661f2cf2014-11-17 10:29:10 -05001817 public void setRingerModeExternal(int ringerMode, String caller) {
John Spurlockaf88a192014-12-23 16:14:44 -05001818 setRingerMode(ringerMode, caller, true /*external*/);
John Spurlock661f2cf2014-11-17 10:29:10 -05001819 }
1820
1821 public void setRingerModeInternal(int ringerMode, String caller) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05001822 enforceVolumeController("setRingerModeInternal");
John Spurlockaf88a192014-12-23 16:14:44 -05001823 setRingerMode(ringerMode, caller, false /*external*/);
John Spurlock661f2cf2014-11-17 10:29:10 -05001824 }
1825
1826 private void setRingerMode(int ringerMode, String caller, boolean external) {
Eric Laurent212532b2014-07-21 15:43:18 -07001827 if (mUseFixedVolume || isPlatformTelevision()) {
Eric Laurent83a017b2013-03-19 18:15:31 -07001828 return;
1829 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001830 if (caller == null || caller.length() == 0) {
1831 throw new IllegalArgumentException("Bad caller: " + caller);
1832 }
John Spurlock97559372014-10-24 16:27:36 -04001833 ensureValidRingerMode(ringerMode);
Eric Laurent24482012012-05-10 09:41:17 -07001834 if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) {
1835 ringerMode = AudioManager.RINGER_MODE_SILENT;
1836 }
John Spurlockaf88a192014-12-23 16:14:44 -05001837 final long identity = Binder.clearCallingIdentity();
1838 try {
1839 synchronized (mSettingsLock) {
1840 final int ringerModeInternal = getRingerModeInternal();
1841 final int ringerModeExternal = getRingerModeExternal();
1842 if (external) {
1843 setRingerModeExt(ringerMode);
1844 if (mRingerModeDelegate != null) {
1845 ringerMode = mRingerModeDelegate.onSetRingerModeExternal(ringerModeExternal,
1846 ringerMode, caller, ringerModeInternal);
1847 }
1848 if (ringerMode != ringerModeInternal) {
1849 setRingerModeInt(ringerMode, true /*persist*/);
1850 }
1851 } else /*internal*/ {
1852 if (ringerMode != ringerModeInternal) {
1853 setRingerModeInt(ringerMode, true /*persist*/);
1854 }
1855 if (mRingerModeDelegate != null) {
1856 ringerMode = mRingerModeDelegate.onSetRingerModeInternal(ringerModeInternal,
1857 ringerMode, caller, ringerModeExternal);
1858 }
1859 setRingerModeExt(ringerMode);
John Spurlock57627792014-12-11 11:29:54 -05001860 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001861 }
John Spurlockaf88a192014-12-23 16:14:44 -05001862 } finally {
1863 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
1865 }
1866
John Spurlock661f2cf2014-11-17 10:29:10 -05001867 private void setRingerModeExt(int ringerMode) {
1868 synchronized(mSettingsLock) {
1869 if (ringerMode == mRingerModeExternal) return;
1870 mRingerModeExternal = ringerMode;
John Spurlocke5b42d92014-10-15 12:03:48 -04001871 }
John Spurlock661f2cf2014-11-17 10:29:10 -05001872 // Send sticky broadcast
John Spurlockbcc10872014-11-28 15:29:21 -05001873 broadcastRingerMode(AudioManager.RINGER_MODE_CHANGED_ACTION, ringerMode);
John Spurlocke5b42d92014-10-15 12:03:48 -04001874 }
1875
Eric Laurent4050c932009-07-08 02:52:14 -07001876 private void setRingerModeInt(int ringerMode, boolean persist) {
John Spurlockbcc10872014-11-28 15:29:21 -05001877 final boolean change;
Glenn Kastenba195eb2011-12-13 09:30:40 -08001878 synchronized(mSettingsLock) {
John Spurlockbcc10872014-11-28 15:29:21 -05001879 change = mRingerMode != ringerMode;
Glenn Kastenba195eb2011-12-13 09:30:40 -08001880 mRingerMode = ringerMode;
1881 }
Jason Parekhb1096152009-03-24 17:48:25 -07001882
Eric Laurent5b4e6542010-03-19 20:02:21 -07001883 // Mute stream if not previously muted by ringer mode and ringer mode
1884 // is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
1885 // Unmute stream if previously muted by ringer mode and ringer mode
1886 // is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
Jason Parekhb1096152009-03-24 17:48:25 -07001887 int numStreamTypes = AudioSystem.getNumStreamTypes();
John Spurlock661f2cf2014-11-17 10:29:10 -05001888 final boolean ringerModeMute = ringerMode == AudioManager.RINGER_MODE_VIBRATE
1889 || ringerMode == AudioManager.RINGER_MODE_SILENT;
Eric Laurent5b4e6542010-03-19 20:02:21 -07001890 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
John Spurlock661f2cf2014-11-17 10:29:10 -05001891 final boolean isMuted = isStreamMutedByRingerMode(streamType);
1892 final boolean shouldMute = ringerModeMute && isStreamAffectedByRingerMode(streamType);
1893 if (isMuted == shouldMute) continue;
1894 if (!shouldMute) {
1895 // unmute
1896 // ring and notifications volume should never be 0 when not silenced
1897 // on voice capable devices or devices that support vibration
1898 if ((isPlatformVoice() || mHasVibrator) &&
1899 mStreamVolumeAlias[streamType] == AudioSystem.STREAM_RING) {
1900 synchronized (VolumeStreamState.class) {
1901 Set set = mStreamStates[streamType].mIndex.entrySet();
1902 Iterator i = set.iterator();
1903 while (i.hasNext()) {
1904 Map.Entry entry = (Map.Entry)i.next();
1905 if ((Integer)entry.getValue() == 0) {
1906 entry.setValue(10);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08001907 }
1908 }
Eric Laurent9e0d25f2015-02-12 17:28:53 -08001909 // Persist volume for stream ring when it is changed here
1910 final int device = getDeviceForStream(streamType);
1911 sendMsg(mAudioHandler,
1912 MSG_PERSIST_VOLUME,
1913 SENDMSG_QUEUE,
1914 device,
1915 0,
1916 mStreamStates[streamType],
1917 PERSIST_DELAY);
Eric Laurentb024c302011-10-14 17:19:27 -07001918 }
Eric Laurent9bcf4012009-06-12 06:09:28 -07001919 }
RoboErik4197cb62015-01-21 15:45:32 -08001920 mStreamStates[streamType].mute(false);
John Spurlock661f2cf2014-11-17 10:29:10 -05001921 mRingerModeMutedStreams &= ~(1 << streamType);
Eric Laurent5b4e6542010-03-19 20:02:21 -07001922 } else {
John Spurlock661f2cf2014-11-17 10:29:10 -05001923 // mute
RoboErik4197cb62015-01-21 15:45:32 -08001924 mStreamStates[streamType].mute(true);
John Spurlock661f2cf2014-11-17 10:29:10 -05001925 mRingerModeMutedStreams |= (1 << streamType);
Jason Parekhb1096152009-03-24 17:48:25 -07001926 }
1927 }
Eric Laurenta553c252009-07-17 12:17:14 -07001928
Jason Parekhb1096152009-03-24 17:48:25 -07001929 // Post a persist ringer mode msg
Eric Laurent4050c932009-07-08 02:52:14 -07001930 if (persist) {
Eric Laurentafbb0472011-12-15 09:04:23 -08001931 sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE,
Eric Laurent4050c932009-07-08 02:52:14 -07001932 SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
1933 }
John Spurlockbcc10872014-11-28 15:29:21 -05001934 if (change) {
1935 // Send sticky broadcast
1936 broadcastRingerMode(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION, ringerMode);
1937 }
Jason Parekhb1096152009-03-24 17:48:25 -07001938 }
1939
Mike Lockwood90631542012-01-06 11:20:37 -05001940 private void restoreMasterVolume() {
Eric Laurent83a017b2013-03-19 18:15:31 -07001941 if (mUseFixedVolume) {
1942 AudioSystem.setMasterVolume(1.0f);
1943 return;
1944 }
Mike Lockwood90631542012-01-06 11:20:37 -05001945 if (mUseMasterVolume) {
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07001946 float volume = Settings.System.getFloatForUser(mContentResolver,
1947 Settings.System.VOLUME_MASTER, -1.0f, UserHandle.USER_CURRENT);
Mike Lockwood90631542012-01-06 11:20:37 -05001948 if (volume >= 0.0f) {
1949 AudioSystem.setMasterVolume(volume);
1950 }
1951 }
1952 }
1953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 /** @see AudioManager#shouldVibrate(int) */
1955 public boolean shouldVibrate(int vibrateType) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07001956 if (!mHasVibrator) return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957
1958 switch (getVibrateSetting(vibrateType)) {
1959
1960 case AudioManager.VIBRATE_SETTING_ON:
John Spurlock57627792014-12-11 11:29:54 -05001961 return getRingerModeExternal() != AudioManager.RINGER_MODE_SILENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962
1963 case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
John Spurlock57627792014-12-11 11:29:54 -05001964 return getRingerModeExternal() == AudioManager.RINGER_MODE_VIBRATE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965
1966 case AudioManager.VIBRATE_SETTING_OFF:
Daniel Sandlerbcac4962010-04-12 13:23:57 -04001967 // return false, even for incoming calls
1968 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969
1970 default:
1971 return false;
1972 }
1973 }
1974
1975 /** @see AudioManager#getVibrateSetting(int) */
1976 public int getVibrateSetting(int vibrateType) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07001977 if (!mHasVibrator) return AudioManager.VIBRATE_SETTING_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 return (mVibrateSetting >> (vibrateType * 2)) & 3;
1979 }
1980
1981 /** @see AudioManager#setVibrateSetting(int, int) */
1982 public void setVibrateSetting(int vibrateType, int vibrateSetting) {
1983
Eric Laurentbffc3d12012-05-07 17:43:49 -07001984 if (!mHasVibrator) return;
1985
John Spurlock61560172015-02-06 19:46:04 -05001986 mVibrateSetting = AudioSystem.getValueForVibrateSetting(mVibrateSetting, vibrateType,
1987 vibrateSetting);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988
1989 // Broadcast change
1990 broadcastVibrateSetting(vibrateType);
1991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993
Eric Laurent9272b4b2010-01-23 17:12:59 -08001994 private class SetModeDeathHandler implements IBinder.DeathRecipient {
1995 private IBinder mCb; // To be notified of client's death
Marco Nelissenf1ddd512011-08-10 14:15:44 -07001996 private int mPid;
Eric Laurent9272b4b2010-01-23 17:12:59 -08001997 private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
1998
Eric Laurent9f103de2011-09-08 15:04:23 -07001999 SetModeDeathHandler(IBinder cb, int pid) {
Eric Laurent9272b4b2010-01-23 17:12:59 -08002000 mCb = cb;
Eric Laurent9f103de2011-09-08 15:04:23 -07002001 mPid = pid;
Eric Laurent9272b4b2010-01-23 17:12:59 -08002002 }
2003
2004 public void binderDied() {
Eric Laurentd7454be2011-09-14 08:45:58 -07002005 int newModeOwnerPid = 0;
Eric Laurent9272b4b2010-01-23 17:12:59 -08002006 synchronized(mSetModeDeathHandlers) {
2007 Log.w(TAG, "setMode() client died");
2008 int index = mSetModeDeathHandlers.indexOf(this);
2009 if (index < 0) {
2010 Log.w(TAG, "unregistered setMode() client died");
2011 } else {
Eric Laurentd7454be2011-09-14 08:45:58 -07002012 newModeOwnerPid = setModeInt(AudioSystem.MODE_NORMAL, mCb, mPid);
Eric Laurent9272b4b2010-01-23 17:12:59 -08002013 }
2014 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002015 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
2016 // SCO connections not started by the application changing the mode
Eric Laurentd7454be2011-09-14 08:45:58 -07002017 if (newModeOwnerPid != 0) {
Eric Laurent6b5e22d2013-03-28 16:10:45 -07002018 final long ident = Binder.clearCallingIdentity();
2019 disconnectBluetoothSco(newModeOwnerPid);
2020 Binder.restoreCallingIdentity(ident);
Eric Laurent9f103de2011-09-08 15:04:23 -07002021 }
Eric Laurent9272b4b2010-01-23 17:12:59 -08002022 }
2023
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002024 public int getPid() {
2025 return mPid;
2026 }
2027
Eric Laurent9272b4b2010-01-23 17:12:59 -08002028 public void setMode(int mode) {
2029 mMode = mode;
2030 }
2031
2032 public int getMode() {
2033 return mMode;
2034 }
2035
2036 public IBinder getBinder() {
2037 return mCb;
2038 }
2039 }
2040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 /** @see AudioManager#setMode(int) */
Eric Laurent9272b4b2010-01-23 17:12:59 -08002042 public void setMode(int mode, IBinder cb) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002043 if (DEBUG_MODE) { Log.v(TAG, "setMode(mode=" + mode + ")"); }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 if (!checkAudioSettingsPermission("setMode()")) {
2045 return;
2046 }
Eric Laurenta553c252009-07-17 12:17:14 -07002047
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07002048 if ( (mode == AudioSystem.MODE_IN_CALL) &&
2049 (mContext.checkCallingOrSelfPermission(
2050 android.Manifest.permission.MODIFY_PHONE_STATE)
2051 != PackageManager.PERMISSION_GRANTED)) {
2052 Log.w(TAG, "MODIFY_PHONE_STATE Permission Denial: setMode(MODE_IN_CALL) from pid="
2053 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
2054 return;
2055 }
2056
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08002057 if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) {
Eric Laurenta553c252009-07-17 12:17:14 -07002058 return;
2059 }
2060
Eric Laurentd7454be2011-09-14 08:45:58 -07002061 int newModeOwnerPid = 0;
Eric Laurent9f103de2011-09-08 15:04:23 -07002062 synchronized(mSetModeDeathHandlers) {
Eric Laurenta553c252009-07-17 12:17:14 -07002063 if (mode == AudioSystem.MODE_CURRENT) {
2064 mode = mMode;
2065 }
Eric Laurentd7454be2011-09-14 08:45:58 -07002066 newModeOwnerPid = setModeInt(mode, cb, Binder.getCallingPid());
Eric Laurent9f103de2011-09-08 15:04:23 -07002067 }
2068 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
2069 // SCO connections not started by the application changing the mode
Eric Laurentd7454be2011-09-14 08:45:58 -07002070 if (newModeOwnerPid != 0) {
2071 disconnectBluetoothSco(newModeOwnerPid);
Eric Laurent9f103de2011-09-08 15:04:23 -07002072 }
2073 }
Jean-Michel Trivi2ade5762010-12-11 13:18:30 -08002074
Eric Laurent9f103de2011-09-08 15:04:23 -07002075 // must be called synchronized on mSetModeDeathHandlers
Eric Laurentd7454be2011-09-14 08:45:58 -07002076 // setModeInt() returns a valid PID if the audio mode was successfully set to
Eric Laurent9f103de2011-09-08 15:04:23 -07002077 // any mode other than NORMAL.
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07002078 private int setModeInt(int mode, IBinder cb, int pid) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002079 if (DEBUG_MODE) { Log.v(TAG, "setModeInt(mode=" + mode + ", pid=" + pid + ")"); }
Eric Laurentd7454be2011-09-14 08:45:58 -07002080 int newModeOwnerPid = 0;
Eric Laurent9f103de2011-09-08 15:04:23 -07002081 if (cb == null) {
2082 Log.e(TAG, "setModeInt() called with null binder");
Eric Laurentd7454be2011-09-14 08:45:58 -07002083 return newModeOwnerPid;
Eric Laurent9f103de2011-09-08 15:04:23 -07002084 }
Jean-Michel Trivi2ade5762010-12-11 13:18:30 -08002085
Eric Laurent9f103de2011-09-08 15:04:23 -07002086 SetModeDeathHandler hdlr = null;
2087 Iterator iter = mSetModeDeathHandlers.iterator();
2088 while (iter.hasNext()) {
2089 SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
2090 if (h.getPid() == pid) {
2091 hdlr = h;
2092 // Remove from client list so that it is re-inserted at top of list
2093 iter.remove();
2094 hdlr.getBinder().unlinkToDeath(hdlr, 0);
2095 break;
2096 }
2097 }
2098 int status = AudioSystem.AUDIO_STATUS_OK;
2099 do {
2100 if (mode == AudioSystem.MODE_NORMAL) {
2101 // get new mode from client at top the list if any
2102 if (!mSetModeDeathHandlers.isEmpty()) {
2103 hdlr = mSetModeDeathHandlers.get(0);
2104 cb = hdlr.getBinder();
2105 mode = hdlr.getMode();
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002106 if (DEBUG_MODE) {
2107 Log.w(TAG, " using mode=" + mode + " instead due to death hdlr at pid="
2108 + hdlr.mPid);
2109 }
Eric Laurentb9c9d262009-05-06 08:13:20 -07002110 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002111 } else {
2112 if (hdlr == null) {
2113 hdlr = new SetModeDeathHandler(cb, pid);
2114 }
2115 // Register for client death notification
2116 try {
2117 cb.linkToDeath(hdlr, 0);
2118 } catch (RemoteException e) {
2119 // Client has died!
2120 Log.w(TAG, "setMode() could not link to "+cb+" binder death");
2121 }
2122
2123 // Last client to call setMode() is always at top of client list
2124 // as required by SetModeDeathHandler.binderDied()
2125 mSetModeDeathHandlers.add(0, hdlr);
2126 hdlr.setMode(mode);
2127 }
2128
2129 if (mode != mMode) {
2130 status = AudioSystem.setPhoneState(mode);
2131 if (status == AudioSystem.AUDIO_STATUS_OK) {
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002132 if (DEBUG_MODE) { Log.v(TAG, " mode successfully set to " + mode); }
Eric Laurent9f103de2011-09-08 15:04:23 -07002133 mMode = mode;
2134 } else {
2135 if (hdlr != null) {
2136 mSetModeDeathHandlers.remove(hdlr);
2137 cb.unlinkToDeath(hdlr, 0);
2138 }
2139 // force reading new top of mSetModeDeathHandlers stack
Jean-Michel Trivi339567d2014-07-29 09:53:34 -07002140 if (DEBUG_MODE) { Log.w(TAG, " mode set to MODE_NORMAL after phoneState pb"); }
Eric Laurent9f103de2011-09-08 15:04:23 -07002141 mode = AudioSystem.MODE_NORMAL;
2142 }
2143 } else {
2144 status = AudioSystem.AUDIO_STATUS_OK;
2145 }
2146 } while (status != AudioSystem.AUDIO_STATUS_OK && !mSetModeDeathHandlers.isEmpty());
2147
2148 if (status == AudioSystem.AUDIO_STATUS_OK) {
2149 if (mode != AudioSystem.MODE_NORMAL) {
Eric Laurentd7454be2011-09-14 08:45:58 -07002150 if (mSetModeDeathHandlers.isEmpty()) {
2151 Log.e(TAG, "setMode() different from MODE_NORMAL with empty mode client stack");
2152 } else {
2153 newModeOwnerPid = mSetModeDeathHandlers.get(0).getPid();
2154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 }
2156 int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08002157 int device = getDeviceForStream(streamType);
Eric Laurent42b041e2013-03-29 11:36:03 -07002158 int index = mStreamStates[mStreamVolumeAlias[streamType]].getIndex(device);
2159 setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, true);
Eric Laurent6d517662012-04-23 18:42:39 -07002160
2161 updateStreamVolumeAlias(true /*updateVolumes*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
Eric Laurentd7454be2011-09-14 08:45:58 -07002163 return newModeOwnerPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165
2166 /** @see AudioManager#getMode() */
2167 public int getMode() {
2168 return mMode;
2169 }
2170
Eric Laurente78fced2013-03-15 16:03:47 -07002171 //==========================================================================================
2172 // Sound Effects
2173 //==========================================================================================
2174
2175 private static final String TAG_AUDIO_ASSETS = "audio_assets";
2176 private static final String ATTR_VERSION = "version";
2177 private static final String TAG_GROUP = "group";
2178 private static final String ATTR_GROUP_NAME = "name";
2179 private static final String TAG_ASSET = "asset";
2180 private static final String ATTR_ASSET_ID = "id";
2181 private static final String ATTR_ASSET_FILE = "file";
2182
2183 private static final String ASSET_FILE_VERSION = "1.0";
2184 private static final String GROUP_TOUCH_SOUNDS = "touch_sounds";
2185
Glenn Kasten167d1a22013-07-23 16:24:41 -07002186 private static final int SOUND_EFFECTS_LOAD_TIMEOUT_MS = 5000;
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002187
2188 class LoadSoundEffectReply {
2189 public int mStatus = 1;
2190 };
2191
Eric Laurente78fced2013-03-15 16:03:47 -07002192 private void loadTouchSoundAssetDefaults() {
2193 SOUND_EFFECT_FILES.add("Effect_Tick.ogg");
2194 for (int i = 0; i < AudioManager.NUM_SOUND_EFFECTS; i++) {
2195 SOUND_EFFECT_FILES_MAP[i][0] = 0;
2196 SOUND_EFFECT_FILES_MAP[i][1] = -1;
2197 }
2198 }
2199
2200 private void loadTouchSoundAssets() {
2201 XmlResourceParser parser = null;
2202
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002203 // only load assets once.
2204 if (!SOUND_EFFECT_FILES.isEmpty()) {
2205 return;
2206 }
2207
Eric Laurente78fced2013-03-15 16:03:47 -07002208 loadTouchSoundAssetDefaults();
2209
2210 try {
2211 parser = mContext.getResources().getXml(com.android.internal.R.xml.audio_assets);
2212
2213 XmlUtils.beginDocument(parser, TAG_AUDIO_ASSETS);
2214 String version = parser.getAttributeValue(null, ATTR_VERSION);
2215 boolean inTouchSoundsGroup = false;
2216
2217 if (ASSET_FILE_VERSION.equals(version)) {
2218 while (true) {
2219 XmlUtils.nextElement(parser);
2220 String element = parser.getName();
2221 if (element == null) {
2222 break;
2223 }
2224 if (element.equals(TAG_GROUP)) {
2225 String name = parser.getAttributeValue(null, ATTR_GROUP_NAME);
2226 if (GROUP_TOUCH_SOUNDS.equals(name)) {
2227 inTouchSoundsGroup = true;
2228 break;
2229 }
2230 }
2231 }
2232 while (inTouchSoundsGroup) {
2233 XmlUtils.nextElement(parser);
2234 String element = parser.getName();
2235 if (element == null) {
2236 break;
2237 }
2238 if (element.equals(TAG_ASSET)) {
2239 String id = parser.getAttributeValue(null, ATTR_ASSET_ID);
2240 String file = parser.getAttributeValue(null, ATTR_ASSET_FILE);
2241 int fx;
2242
2243 try {
2244 Field field = AudioManager.class.getField(id);
2245 fx = field.getInt(null);
2246 } catch (Exception e) {
2247 Log.w(TAG, "Invalid touch sound ID: "+id);
2248 continue;
2249 }
2250
2251 int i = SOUND_EFFECT_FILES.indexOf(file);
2252 if (i == -1) {
2253 i = SOUND_EFFECT_FILES.size();
2254 SOUND_EFFECT_FILES.add(file);
2255 }
2256 SOUND_EFFECT_FILES_MAP[fx][0] = i;
2257 } else {
2258 break;
2259 }
2260 }
2261 }
2262 } catch (Resources.NotFoundException e) {
2263 Log.w(TAG, "audio assets file not found", e);
2264 } catch (XmlPullParserException e) {
2265 Log.w(TAG, "XML parser exception reading touch sound assets", e);
2266 } catch (IOException e) {
2267 Log.w(TAG, "I/O exception reading touch sound assets", e);
2268 } finally {
2269 if (parser != null) {
2270 parser.close();
2271 }
2272 }
2273 }
2274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 /** @see AudioManager#playSoundEffect(int) */
2276 public void playSoundEffect(int effectType) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002277 playSoundEffectVolume(effectType, -1.0f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 }
2279
2280 /** @see AudioManager#playSoundEffect(int, float) */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 public void playSoundEffectVolume(int effectType, float volume) {
Natalie Silvanovich559c76d2014-05-01 10:16:24 -07002282 if (effectType >= AudioManager.NUM_SOUND_EFFECTS || effectType < 0) {
2283 Log.w(TAG, "AudioService effectType value " + effectType + " out of range");
2284 return;
2285 }
2286
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002287 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_QUEUE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 effectType, (int) (volume * 1000), null, 0);
2289 }
2290
2291 /**
2292 * Loads samples into the soundpool.
Glenn Kasten5c17a822011-11-30 09:41:01 -08002293 * This method must be called at first when sound effects are enabled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 */
2295 public boolean loadSoundEffects() {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002296 int attempts = 3;
2297 LoadSoundEffectReply reply = new LoadSoundEffectReply();
Eric Laurenta60e2122010-12-28 16:49:07 -08002298
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002299 synchronized (reply) {
2300 sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, reply, 0);
2301 while ((reply.mStatus == 1) && (attempts-- > 0)) {
Eric Laurent117b7bb2011-01-16 17:07:27 -08002302 try {
Glenn Kasten167d1a22013-07-23 16:24:41 -07002303 reply.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002304 } catch (InterruptedException e) {
2305 Log.w(TAG, "loadSoundEffects Interrupted while waiting sound pool loaded.");
Eric Laurent117b7bb2011-01-16 17:07:27 -08002306 }
Eric Laurenta60e2122010-12-28 16:49:07 -08002307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002309 return (reply.mStatus == 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311
2312 /**
2313 * Unloads samples from the sound pool.
2314 * This method can be called to free some memory when
2315 * sound effects are disabled.
2316 */
2317 public void unloadSoundEffects() {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002318 sendMsg(mAudioHandler, MSG_UNLOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 }
2320
Eric Laurenta60e2122010-12-28 16:49:07 -08002321 class SoundPoolListenerThread extends Thread {
2322 public SoundPoolListenerThread() {
2323 super("SoundPoolListenerThread");
2324 }
2325
2326 @Override
2327 public void run() {
2328
2329 Looper.prepare();
2330 mSoundPoolLooper = Looper.myLooper();
2331
2332 synchronized (mSoundEffectsLock) {
2333 if (mSoundPool != null) {
2334 mSoundPoolCallBack = new SoundPoolCallback();
2335 mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack);
2336 }
2337 mSoundEffectsLock.notify();
2338 }
2339 Looper.loop();
2340 }
2341 }
2342
2343 private final class SoundPoolCallback implements
2344 android.media.SoundPool.OnLoadCompleteListener {
2345
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002346 int mStatus = 1; // 1 means neither error nor last sample loaded yet
2347 List<Integer> mSamples = new ArrayList<Integer>();
Eric Laurenta60e2122010-12-28 16:49:07 -08002348
2349 public int status() {
2350 return mStatus;
2351 }
2352
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002353 public void setSamples(int[] samples) {
2354 for (int i = 0; i < samples.length; i++) {
2355 // do not wait ack for samples rejected upfront by SoundPool
2356 if (samples[i] > 0) {
2357 mSamples.add(samples[i]);
2358 }
2359 }
Eric Laurenta60e2122010-12-28 16:49:07 -08002360 }
2361
2362 public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
2363 synchronized (mSoundEffectsLock) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002364 int i = mSamples.indexOf(sampleId);
2365 if (i >= 0) {
2366 mSamples.remove(i);
Eric Laurenta60e2122010-12-28 16:49:07 -08002367 }
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07002368 if ((status != 0) || mSamples. isEmpty()) {
2369 mStatus = status;
Eric Laurenta60e2122010-12-28 16:49:07 -08002370 mSoundEffectsLock.notify();
2371 }
2372 }
2373 }
2374 }
2375
Eric Laurent4050c932009-07-08 02:52:14 -07002376 /** @see AudioManager#reloadAudioSettings() */
2377 public void reloadAudioSettings() {
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07002378 readAudioSettings(false /*userSwitch*/);
2379 }
2380
2381 private void readAudioSettings(boolean userSwitch) {
Eric Laurent4050c932009-07-08 02:52:14 -07002382 // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
2383 readPersistedSettings();
2384
2385 // restore volume settings
2386 int numStreamTypes = AudioSystem.getNumStreamTypes();
2387 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
2388 VolumeStreamState streamState = mStreamStates[streamType];
2389
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07002390 if (userSwitch && mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) {
2391 continue;
2392 }
2393
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07002394 streamState.readSettings();
2395 synchronized (VolumeStreamState.class) {
Eric Laurent3172d5e2012-05-09 11:38:16 -07002396 // unmute stream that was muted but is not affect by mute anymore
RoboErik4197cb62015-01-21 15:45:32 -08002397 if (streamState.mIsMuted && ((!isStreamAffectedByMute(streamType) &&
Eric Laurent83a017b2013-03-19 18:15:31 -07002398 !isStreamMutedByRingerMode(streamType)) || mUseFixedVolume)) {
RoboErik4197cb62015-01-21 15:45:32 -08002399 streamState.mIsMuted = false;
Eric Laurent4050c932009-07-08 02:52:14 -07002400 }
Eric Laurent4050c932009-07-08 02:52:14 -07002401 }
2402 }
2403
Eric Laurent33902db2012-10-07 16:15:07 -07002404 // apply new ringer mode before checking volume for alias streams so that streams
2405 // muted by ringer mode have the correct volume
John Spurlock661f2cf2014-11-17 10:29:10 -05002406 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent33902db2012-10-07 16:15:07 -07002407
Eric Laurent212532b2014-07-21 15:43:18 -07002408 checkAllFixedVolumeDevices();
Eric Laurent24482012012-05-10 09:41:17 -07002409 checkAllAliasStreamVolumes();
2410
Eric Laurentd640bd32012-09-28 18:01:48 -07002411 synchronized (mSafeMediaVolumeState) {
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002412 mMusicActiveMs = MathUtils.constrain(Settings.Secure.getIntForUser(mContentResolver,
2413 Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, 0, UserHandle.USER_CURRENT),
2414 0, UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX);
Eric Laurentd640bd32012-09-28 18:01:48 -07002415 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) {
Eric Laurentf1a457d2012-09-20 16:27:23 -07002416 enforceSafeMediaVolume();
2417 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07002418 }
Eric Laurent4050c932009-07-08 02:52:14 -07002419 }
2420
Dianne Hackborn961cae92013-03-20 14:59:43 -07002421 /** @see AudioManager#setSpeakerphoneOn(boolean) */
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002422 public void setSpeakerphoneOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -07002423 if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
2424 return;
2425 }
Johan Gustavsson7337bee2013-03-01 15:53:30 +01002426
2427 if (on) {
2428 if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
2429 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
2430 AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE, null, 0);
2431 }
2432 mForcedUseForComm = AudioSystem.FORCE_SPEAKER;
2433 } else if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER){
2434 mForcedUseForComm = AudioSystem.FORCE_NONE;
2435 }
Eric Laurentfa640152011-03-12 15:59:51 -08002436
Eric Laurentafbb0472011-12-15 09:04:23 -08002437 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002438 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002439 }
2440
2441 /** @see AudioManager#isSpeakerphoneOn() */
2442 public boolean isSpeakerphoneOn() {
Eric Laurentfa640152011-03-12 15:59:51 -08002443 return (mForcedUseForComm == AudioSystem.FORCE_SPEAKER);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002444 }
2445
Dianne Hackborn961cae92013-03-20 14:59:43 -07002446 /** @see AudioManager#setBluetoothScoOn(boolean) */
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002447 public void setBluetoothScoOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -07002448 if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
2449 return;
2450 }
Johan Gustavsson7337bee2013-03-01 15:53:30 +01002451
2452 if (on) {
2453 mForcedUseForComm = AudioSystem.FORCE_BT_SCO;
2454 } else if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
2455 mForcedUseForComm = AudioSystem.FORCE_NONE;
2456 }
Eric Laurentfa640152011-03-12 15:59:51 -08002457
Eric Laurentafbb0472011-12-15 09:04:23 -08002458 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002459 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
Eric Laurentafbb0472011-12-15 09:04:23 -08002460 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
Eric Laurentfa640152011-03-12 15:59:51 -08002461 AudioSystem.FOR_RECORD, mForcedUseForComm, null, 0);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002462 }
2463
2464 /** @see AudioManager#isBluetoothScoOn() */
2465 public boolean isBluetoothScoOn() {
Eric Laurentfa640152011-03-12 15:59:51 -08002466 return (mForcedUseForComm == AudioSystem.FORCE_BT_SCO);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07002467 }
2468
Dianne Hackborn961cae92013-03-20 14:59:43 -07002469 /** @see AudioManager#setBluetoothA2dpOn(boolean) */
Eric Laurent78472112012-05-21 08:57:21 -07002470 public void setBluetoothA2dpOn(boolean on) {
Eric Laurentc390bed2012-07-03 12:24:05 -07002471 synchronized (mBluetoothA2dpEnabledLock) {
2472 mBluetoothA2dpEnabled = on;
2473 sendMsg(mAudioHandler, MSG_SET_FORCE_BT_A2DP_USE, SENDMSG_QUEUE,
2474 AudioSystem.FOR_MEDIA,
2475 mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP,
2476 null, 0);
2477 }
Eric Laurent78472112012-05-21 08:57:21 -07002478 }
2479
2480 /** @see AudioManager#isBluetoothA2dpOn() */
2481 public boolean isBluetoothA2dpOn() {
2482 synchronized (mBluetoothA2dpEnabledLock) {
2483 return mBluetoothA2dpEnabled;
2484 }
2485 }
2486
Eric Laurent3def1ee2010-03-17 23:26:26 -07002487 /** @see AudioManager#startBluetoothSco() */
Eric Laurent83900752014-05-15 15:14:22 -07002488 public void startBluetoothSco(IBinder cb, int targetSdkVersion) {
2489 int scoAudioMode =
2490 (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR2) ?
Liejun Taof4e51d82014-07-16 11:18:29 -07002491 SCO_MODE_VIRTUAL_CALL : SCO_MODE_UNDEFINED;
Eric Laurent83900752014-05-15 15:14:22 -07002492 startBluetoothScoInt(cb, scoAudioMode);
2493 }
2494
2495 /** @see AudioManager#startBluetoothScoVirtualCall() */
2496 public void startBluetoothScoVirtualCall(IBinder cb) {
2497 startBluetoothScoInt(cb, SCO_MODE_VIRTUAL_CALL);
2498 }
2499
2500 void startBluetoothScoInt(IBinder cb, int scoAudioMode){
Eric Laurentdc03c612011-04-01 10:59:41 -07002501 if (!checkAudioSettingsPermission("startBluetoothSco()") ||
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002502 !mSystemReady) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002503 return;
2504 }
Eric Laurent854938a2011-02-22 12:05:20 -08002505 ScoClient client = getScoClient(cb, true);
Eric Laurentf5a1fc32013-03-11 18:52:57 -07002506 // The calling identity must be cleared before calling ScoClient.incCount().
2507 // inCount() calls requestScoState() which in turn can call BluetoothHeadset APIs
2508 // and this must be done on behalf of system server to make sure permissions are granted.
2509 // The caller identity must be cleared after getScoClient() because it is needed if a new
2510 // client is created.
2511 final long ident = Binder.clearCallingIdentity();
Eric Laurent83900752014-05-15 15:14:22 -07002512 client.incCount(scoAudioMode);
Eric Laurent2a57ca92013-03-07 17:29:27 -08002513 Binder.restoreCallingIdentity(ident);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002514 }
2515
2516 /** @see AudioManager#stopBluetoothSco() */
2517 public void stopBluetoothSco(IBinder cb){
Eric Laurentdc03c612011-04-01 10:59:41 -07002518 if (!checkAudioSettingsPermission("stopBluetoothSco()") ||
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002519 !mSystemReady) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002520 return;
2521 }
Eric Laurent854938a2011-02-22 12:05:20 -08002522 ScoClient client = getScoClient(cb, false);
Eric Laurentf5a1fc32013-03-11 18:52:57 -07002523 // The calling identity must be cleared before calling ScoClient.decCount().
2524 // decCount() calls requestScoState() which in turn can call BluetoothHeadset APIs
2525 // and this must be done on behalf of system server to make sure permissions are granted.
2526 final long ident = Binder.clearCallingIdentity();
Eric Laurent854938a2011-02-22 12:05:20 -08002527 if (client != null) {
2528 client.decCount();
2529 }
Eric Laurent2a57ca92013-03-07 17:29:27 -08002530 Binder.restoreCallingIdentity(ident);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002531 }
2532
Eric Laurent78472112012-05-21 08:57:21 -07002533
Eric Laurent3def1ee2010-03-17 23:26:26 -07002534 private class ScoClient implements IBinder.DeathRecipient {
2535 private IBinder mCb; // To be notified of client's death
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002536 private int mCreatorPid;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002537 private int mStartcount; // number of SCO connections started by this client
2538
2539 ScoClient(IBinder cb) {
2540 mCb = cb;
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002541 mCreatorPid = Binder.getCallingPid();
Eric Laurent3def1ee2010-03-17 23:26:26 -07002542 mStartcount = 0;
2543 }
2544
2545 public void binderDied() {
2546 synchronized(mScoClients) {
2547 Log.w(TAG, "SCO client died");
2548 int index = mScoClients.indexOf(this);
2549 if (index < 0) {
2550 Log.w(TAG, "unregistered SCO client died");
2551 } else {
2552 clearCount(true);
2553 mScoClients.remove(this);
2554 }
2555 }
2556 }
2557
Eric Laurent83900752014-05-15 15:14:22 -07002558 public void incCount(int scoAudioMode) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002559 synchronized(mScoClients) {
Eric Laurent83900752014-05-15 15:14:22 -07002560 requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED, scoAudioMode);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002561 if (mStartcount == 0) {
2562 try {
2563 mCb.linkToDeath(this, 0);
2564 } catch (RemoteException e) {
2565 // client has already died!
2566 Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death");
2567 }
2568 }
2569 mStartcount++;
2570 }
2571 }
2572
2573 public void decCount() {
2574 synchronized(mScoClients) {
2575 if (mStartcount == 0) {
2576 Log.w(TAG, "ScoClient.decCount() already 0");
2577 } else {
2578 mStartcount--;
2579 if (mStartcount == 0) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07002580 try {
2581 mCb.unlinkToDeath(this, 0);
2582 } catch (NoSuchElementException e) {
2583 Log.w(TAG, "decCount() going to 0 but not registered to binder");
2584 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002585 }
Eric Laurentc18c9132013-04-12 17:24:56 -07002586 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, 0);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002587 }
2588 }
2589 }
2590
2591 public void clearCount(boolean stopSco) {
2592 synchronized(mScoClients) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07002593 if (mStartcount != 0) {
2594 try {
2595 mCb.unlinkToDeath(this, 0);
2596 } catch (NoSuchElementException e) {
2597 Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
2598 }
2599 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002600 mStartcount = 0;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002601 if (stopSco) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002602 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, 0);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002603 }
2604 }
2605 }
2606
2607 public int getCount() {
2608 return mStartcount;
2609 }
2610
2611 public IBinder getBinder() {
2612 return mCb;
2613 }
2614
Eric Laurentd7454be2011-09-14 08:45:58 -07002615 public int getPid() {
2616 return mCreatorPid;
2617 }
2618
Eric Laurent3def1ee2010-03-17 23:26:26 -07002619 public int totalCount() {
2620 synchronized(mScoClients) {
2621 int count = 0;
2622 int size = mScoClients.size();
2623 for (int i = 0; i < size; i++) {
2624 count += mScoClients.get(i).getCount();
2625 }
2626 return count;
2627 }
2628 }
2629
Eric Laurent83900752014-05-15 15:14:22 -07002630 private void requestScoState(int state, int scoAudioMode) {
Eric Laurent62ef7672010-11-24 10:58:32 -08002631 checkScoAudioState();
Eric Laurentdc03c612011-04-01 10:59:41 -07002632 if (totalCount() == 0) {
2633 if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
2634 // Make sure that the state transitions to CONNECTING even if we cannot initiate
2635 // the connection.
2636 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
2637 // Accept SCO audio activation only in NORMAL audio mode or if the mode is
Marco Nelissenf1ddd512011-08-10 14:15:44 -07002638 // currently controlled by the same client process.
Eric Laurent9f103de2011-09-08 15:04:23 -07002639 synchronized(mSetModeDeathHandlers) {
2640 if ((mSetModeDeathHandlers.isEmpty() ||
2641 mSetModeDeathHandlers.get(0).getPid() == mCreatorPid) &&
2642 (mScoAudioState == SCO_STATE_INACTIVE ||
2643 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
2644 if (mScoAudioState == SCO_STATE_INACTIVE) {
Eric Laurent83900752014-05-15 15:14:22 -07002645 mScoAudioMode = scoAudioMode;
Liejun Taof4e51d82014-07-16 11:18:29 -07002646 if (scoAudioMode == SCO_MODE_UNDEFINED) {
Andre Eisenbach570cc532014-10-28 17:03:18 -07002647 if (mBluetoothHeadsetDevice != null) {
2648 mScoAudioMode = new Integer(Settings.Global.getInt(
2649 mContentResolver,
2650 "bluetooth_sco_channel_"+
2651 mBluetoothHeadsetDevice.getAddress(),
2652 SCO_MODE_VIRTUAL_CALL));
2653 if (mScoAudioMode > SCO_MODE_MAX || mScoAudioMode < 0) {
2654 mScoAudioMode = SCO_MODE_VIRTUAL_CALL;
2655 }
2656 } else {
2657 mScoAudioMode = SCO_MODE_RAW;
Liejun Taof4e51d82014-07-16 11:18:29 -07002658 }
2659 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002660 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
Liejun Taof4e51d82014-07-16 11:18:29 -07002661 boolean status = false;
Eric Laurentc18c9132013-04-12 17:24:56 -07002662 if (mScoAudioMode == SCO_MODE_RAW) {
2663 status = mBluetoothHeadset.connectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002664 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002665 status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
2666 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002667 } else if (mScoAudioMode == SCO_MODE_VR) {
2668 status = mBluetoothHeadset.startVoiceRecognition(
2669 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002670 }
Liejun Taof4e51d82014-07-16 11:18:29 -07002671
Eric Laurentc18c9132013-04-12 17:24:56 -07002672 if (status) {
Eric Laurent9f103de2011-09-08 15:04:23 -07002673 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
2674 } else {
2675 broadcastScoConnectionState(
2676 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2677 }
2678 } else if (getBluetoothHeadset()) {
2679 mScoAudioState = SCO_STATE_ACTIVATE_REQ;
Eric Laurentdc03c612011-04-01 10:59:41 -07002680 }
Eric Laurent9f103de2011-09-08 15:04:23 -07002681 } else {
2682 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
2683 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED);
Eric Laurentdc03c612011-04-01 10:59:41 -07002684 }
2685 } else {
Eric Laurent9f103de2011-09-08 15:04:23 -07002686 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
Eric Laurentdc03c612011-04-01 10:59:41 -07002687 }
Eric Laurentdc03c612011-04-01 10:59:41 -07002688 }
Eric Laurent62ef7672010-11-24 10:58:32 -08002689 } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED &&
Eric Laurentdc03c612011-04-01 10:59:41 -07002690 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
2691 mScoAudioState == SCO_STATE_ACTIVATE_REQ)) {
2692 if (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) {
Marco Nelissen671db6f2011-09-06 16:29:12 -07002693 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
Liejun Taof4e51d82014-07-16 11:18:29 -07002694 boolean status = false;
Eric Laurentc18c9132013-04-12 17:24:56 -07002695 if (mScoAudioMode == SCO_MODE_RAW) {
2696 status = mBluetoothHeadset.disconnectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002697 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002698 status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
2699 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002700 } else if (mScoAudioMode == SCO_MODE_VR) {
2701 status = mBluetoothHeadset.stopVoiceRecognition(
2702 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002703 }
Liejun Taof4e51d82014-07-16 11:18:29 -07002704
Eric Laurentc18c9132013-04-12 17:24:56 -07002705 if (!status) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002706 mScoAudioState = SCO_STATE_INACTIVE;
2707 broadcastScoConnectionState(
2708 AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2709 }
2710 } else if (getBluetoothHeadset()) {
2711 mScoAudioState = SCO_STATE_DEACTIVATE_REQ;
2712 }
2713 } else {
2714 mScoAudioState = SCO_STATE_INACTIVE;
2715 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2716 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002717 }
2718 }
2719 }
2720 }
2721
Eric Laurent62ef7672010-11-24 10:58:32 -08002722 private void checkScoAudioState() {
2723 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null &&
Eric Laurentdc03c612011-04-01 10:59:41 -07002724 mScoAudioState == SCO_STATE_INACTIVE &&
Eric Laurent62ef7672010-11-24 10:58:32 -08002725 mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice)
2726 != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
2727 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2728 }
2729 }
2730
Eric Laurent854938a2011-02-22 12:05:20 -08002731 private ScoClient getScoClient(IBinder cb, boolean create) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002732 synchronized(mScoClients) {
Eric Laurent854938a2011-02-22 12:05:20 -08002733 ScoClient client = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002734 int size = mScoClients.size();
2735 for (int i = 0; i < size; i++) {
2736 client = mScoClients.get(i);
2737 if (client.getBinder() == cb)
2738 return client;
2739 }
Eric Laurent854938a2011-02-22 12:05:20 -08002740 if (create) {
2741 client = new ScoClient(cb);
2742 mScoClients.add(client);
2743 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07002744 return client;
2745 }
2746 }
2747
Eric Laurentd7454be2011-09-14 08:45:58 -07002748 public void clearAllScoClients(int exceptPid, boolean stopSco) {
Eric Laurent3def1ee2010-03-17 23:26:26 -07002749 synchronized(mScoClients) {
Eric Laurent854938a2011-02-22 12:05:20 -08002750 ScoClient savedClient = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002751 int size = mScoClients.size();
2752 for (int i = 0; i < size; i++) {
Eric Laurent854938a2011-02-22 12:05:20 -08002753 ScoClient cl = mScoClients.get(i);
Eric Laurentd7454be2011-09-14 08:45:58 -07002754 if (cl.getPid() != exceptPid) {
Eric Laurent854938a2011-02-22 12:05:20 -08002755 cl.clearCount(stopSco);
2756 } else {
2757 savedClient = cl;
2758 }
2759 }
2760 mScoClients.clear();
2761 if (savedClient != null) {
2762 mScoClients.add(savedClient);
Eric Laurent3def1ee2010-03-17 23:26:26 -07002763 }
2764 }
2765 }
2766
Eric Laurentdc03c612011-04-01 10:59:41 -07002767 private boolean getBluetoothHeadset() {
2768 boolean result = false;
2769 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
2770 if (adapter != null) {
2771 result = adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
2772 BluetoothProfile.HEADSET);
2773 }
2774 // If we could not get a bluetooth headset proxy, send a failure message
2775 // without delay to reset the SCO audio state and clear SCO clients.
2776 // If we could get a proxy, send a delayed failure message that will reset our state
2777 // in case we don't receive onServiceConnected().
Eric Laurentafbb0472011-12-15 09:04:23 -08002778 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurentdc03c612011-04-01 10:59:41 -07002779 SENDMSG_REPLACE, 0, 0, null, result ? BT_HEADSET_CNCT_TIMEOUT_MS : 0);
2780 return result;
2781 }
2782
Eric Laurentd7454be2011-09-14 08:45:58 -07002783 private void disconnectBluetoothSco(int exceptPid) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002784 synchronized(mScoClients) {
2785 checkScoAudioState();
2786 if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL ||
2787 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
2788 if (mBluetoothHeadsetDevice != null) {
2789 if (mBluetoothHeadset != null) {
2790 if (!mBluetoothHeadset.stopVoiceRecognition(
Eric Laurentb06ac832011-05-25 15:55:18 -07002791 mBluetoothHeadsetDevice)) {
Eric Laurentafbb0472011-12-15 09:04:23 -08002792 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurentdc03c612011-04-01 10:59:41 -07002793 SENDMSG_REPLACE, 0, 0, null, 0);
2794 }
2795 } else if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL &&
2796 getBluetoothHeadset()) {
2797 mScoAudioState = SCO_STATE_DEACTIVATE_EXT_REQ;
2798 }
2799 }
2800 } else {
Eric Laurentd7454be2011-09-14 08:45:58 -07002801 clearAllScoClients(exceptPid, true);
Eric Laurentdc03c612011-04-01 10:59:41 -07002802 }
2803 }
2804 }
2805
2806 private void resetBluetoothSco() {
2807 synchronized(mScoClients) {
Eric Laurentd7454be2011-09-14 08:45:58 -07002808 clearAllScoClients(0, false);
Eric Laurentdc03c612011-04-01 10:59:41 -07002809 mScoAudioState = SCO_STATE_INACTIVE;
2810 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2811 }
2812 }
2813
2814 private void broadcastScoConnectionState(int state) {
Eric Laurent2a57ca92013-03-07 17:29:27 -08002815 sendMsg(mAudioHandler, MSG_BROADCAST_BT_CONNECTION_STATE,
2816 SENDMSG_QUEUE, state, 0, null, 0);
2817 }
2818
2819 private void onBroadcastScoConnectionState(int state) {
Eric Laurentdc03c612011-04-01 10:59:41 -07002820 if (state != mScoConnectionState) {
2821 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
2822 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
2823 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE,
2824 mScoConnectionState);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002825 sendStickyBroadcastToAll(newIntent);
Eric Laurentdc03c612011-04-01 10:59:41 -07002826 mScoConnectionState = state;
2827 }
2828 }
2829
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07002830 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
2831 new BluetoothProfile.ServiceListener() {
2832 public void onServiceConnected(int profile, BluetoothProfile proxy) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002833 BluetoothDevice btDevice;
2834 List<BluetoothDevice> deviceList;
2835 switch(profile) {
2836 case BluetoothProfile.A2DP:
seunghwan.hong4fe77952014-10-29 17:43:20 +09002837 synchronized (mConnectedDevices) {
2838 synchronized (mA2dpAvrcpLock) {
2839 mA2dp = (BluetoothA2dp) proxy;
2840 deviceList = mA2dp.getConnectedDevices();
2841 if (deviceList.size() > 0) {
2842 btDevice = deviceList.get(0);
John Du5a0cf7a2013-07-19 11:30:34 -07002843 int state = mA2dp.getConnectionState(btDevice);
2844 int delay = checkSendBecomingNoisyIntent(
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002845 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2846 (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
John Du5a0cf7a2013-07-19 11:30:34 -07002847 queueMsgUnderWakeLock(mAudioHandler,
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002848 MSG_SET_A2DP_SINK_CONNECTION_STATE,
John Du5a0cf7a2013-07-19 11:30:34 -07002849 state,
2850 0,
2851 btDevice,
2852 delay);
2853 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07002854 }
Eric Laurent62ef7672010-11-24 10:58:32 -08002855 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002856 break;
2857
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002858 case BluetoothProfile.A2DP_SINK:
2859 deviceList = proxy.getConnectedDevices();
2860 if (deviceList.size() > 0) {
2861 btDevice = deviceList.get(0);
2862 synchronized (mConnectedDevices) {
2863 int state = proxy.getConnectionState(btDevice);
2864 queueMsgUnderWakeLock(mAudioHandler,
2865 MSG_SET_A2DP_SRC_CONNECTION_STATE,
2866 state,
2867 0,
2868 btDevice,
2869 0 /* delay */);
2870 }
2871 }
2872 break;
2873
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002874 case BluetoothProfile.HEADSET:
2875 synchronized (mScoClients) {
2876 // Discard timeout message
2877 mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED);
2878 mBluetoothHeadset = (BluetoothHeadset) proxy;
2879 deviceList = mBluetoothHeadset.getConnectedDevices();
2880 if (deviceList.size() > 0) {
2881 mBluetoothHeadsetDevice = deviceList.get(0);
2882 } else {
2883 mBluetoothHeadsetDevice = null;
2884 }
2885 // Refresh SCO audio state
2886 checkScoAudioState();
2887 // Continue pending action if any
2888 if (mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
2889 mScoAudioState == SCO_STATE_DEACTIVATE_REQ ||
2890 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
2891 boolean status = false;
2892 if (mBluetoothHeadsetDevice != null) {
2893 switch (mScoAudioState) {
2894 case SCO_STATE_ACTIVATE_REQ:
2895 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
Eric Laurentc18c9132013-04-12 17:24:56 -07002896 if (mScoAudioMode == SCO_MODE_RAW) {
2897 status = mBluetoothHeadset.connectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002898 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002899 status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
2900 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002901 } else if (mScoAudioMode == SCO_MODE_VR) {
2902 status = mBluetoothHeadset.startVoiceRecognition(
2903 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002904 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002905 break;
2906 case SCO_STATE_DEACTIVATE_REQ:
Eric Laurentc18c9132013-04-12 17:24:56 -07002907 if (mScoAudioMode == SCO_MODE_RAW) {
2908 status = mBluetoothHeadset.disconnectAudio();
Liejun Taof4e51d82014-07-16 11:18:29 -07002909 } else if (mScoAudioMode == SCO_MODE_VIRTUAL_CALL) {
Eric Laurentc18c9132013-04-12 17:24:56 -07002910 status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
2911 mBluetoothHeadsetDevice);
Liejun Taof4e51d82014-07-16 11:18:29 -07002912 } else if (mScoAudioMode == SCO_MODE_VR) {
2913 status = mBluetoothHeadset.stopVoiceRecognition(
2914 mBluetoothHeadsetDevice);
Eric Laurentc18c9132013-04-12 17:24:56 -07002915 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002916 break;
2917 case SCO_STATE_DEACTIVATE_EXT_REQ:
2918 status = mBluetoothHeadset.stopVoiceRecognition(
2919 mBluetoothHeadsetDevice);
2920 }
2921 }
2922 if (!status) {
Eric Laurentafbb0472011-12-15 09:04:23 -08002923 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002924 SENDMSG_REPLACE, 0, 0, null, 0);
Eric Laurentdc03c612011-04-01 10:59:41 -07002925 }
2926 }
Eric Laurentdc03c612011-04-01 10:59:41 -07002927 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002928 break;
2929
2930 default:
2931 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002932 }
2933 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07002934 public void onServiceDisconnected(int profile) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002935 switch(profile) {
2936 case BluetoothProfile.A2DP:
seunghwan.hong4fe77952014-10-29 17:43:20 +09002937 synchronized (mConnectedDevices) {
2938 synchronized (mA2dpAvrcpLock) {
2939 mA2dp = null;
John Du5a0cf7a2013-07-19 11:30:34 -07002940 if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) {
2941 makeA2dpDeviceUnavailableNow(
2942 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP));
2943 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002944 }
2945 }
2946 break;
2947
Mike Lockwood0a40ec22014-05-21 10:08:50 -07002948 case BluetoothProfile.A2DP_SINK:
2949 synchronized (mConnectedDevices) {
2950 if (mConnectedDevices.containsKey(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP)) {
2951 makeA2dpSrcUnavailable(
2952 mConnectedDevices.get(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP));
2953 }
2954 }
2955 break;
2956
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08002957 case BluetoothProfile.HEADSET:
2958 synchronized (mScoClients) {
2959 mBluetoothHeadset = null;
2960 }
2961 break;
2962
2963 default:
2964 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07002965 }
2966 }
2967 };
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002968
Eric Laurentc34dcc12012-09-10 13:51:52 -07002969 private void onCheckMusicActive() {
Eric Laurentd640bd32012-09-28 18:01:48 -07002970 synchronized (mSafeMediaVolumeState) {
2971 if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07002972 int device = getDeviceForStream(AudioSystem.STREAM_MUSIC);
2973
2974 if ((device & mSafeMediaVolumeDevices) != 0) {
2975 sendMsg(mAudioHandler,
2976 MSG_CHECK_MUSIC_ACTIVE,
2977 SENDMSG_REPLACE,
Eric Laurentf1a457d2012-09-20 16:27:23 -07002978 0,
Eric Laurentc34dcc12012-09-10 13:51:52 -07002979 0,
2980 null,
2981 MUSIC_ACTIVE_POLL_PERIOD_MS);
Eric Laurent42b041e2013-03-29 11:36:03 -07002982 int index = mStreamStates[AudioSystem.STREAM_MUSIC].getIndex(device);
Eric Laurentf1a457d2012-09-20 16:27:23 -07002983 if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0) &&
2984 (index > mSafeMediaVolumeIndex)) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07002985 // Approximate cumulative active music time
2986 mMusicActiveMs += MUSIC_ACTIVE_POLL_PERIOD_MS;
2987 if (mMusicActiveMs > UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX) {
2988 setSafeMediaVolumeEnabled(true);
2989 mMusicActiveMs = 0;
Eric Laurentc34dcc12012-09-10 13:51:52 -07002990 }
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002991 saveMusicActiveMs();
Eric Laurentc34dcc12012-09-10 13:51:52 -07002992 }
2993 }
2994 }
2995 }
2996 }
2997
John Spurlockaa5ee4d2014-07-25 13:05:12 -04002998 private void saveMusicActiveMs() {
2999 mAudioHandler.obtainMessage(MSG_PERSIST_MUSIC_ACTIVE_MS, mMusicActiveMs, 0).sendToTarget();
3000 }
3001
Eric Laurentd640bd32012-09-28 18:01:48 -07003002 private void onConfigureSafeVolume(boolean force) {
3003 synchronized (mSafeMediaVolumeState) {
3004 int mcc = mContext.getResources().getConfiguration().mcc;
3005 if ((mMcc != mcc) || ((mMcc == 0) && force)) {
3006 mSafeMediaVolumeIndex = mContext.getResources().getInteger(
3007 com.android.internal.R.integer.config_safe_media_volume_index) * 10;
John Spurlock35134602014-07-24 18:10:48 -04003008 boolean safeMediaVolumeEnabled =
3009 SystemProperties.getBoolean("audio.safemedia.force", false)
3010 || mContext.getResources().getBoolean(
3011 com.android.internal.R.bool.config_safe_media_volume_enabled);
Eric Laurent05274f32012-11-29 12:48:18 -08003012
3013 // The persisted state is either "disabled" or "active": this is the state applied
3014 // next time we boot and cannot be "inactive"
3015 int persistedState;
Eric Laurentd640bd32012-09-28 18:01:48 -07003016 if (safeMediaVolumeEnabled) {
Eric Laurent05274f32012-11-29 12:48:18 -08003017 persistedState = SAFE_MEDIA_VOLUME_ACTIVE;
3018 // The state can already be "inactive" here if the user has forced it before
3019 // the 30 seconds timeout for forced configuration. In this case we don't reset
3020 // it to "active".
3021 if (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_INACTIVE) {
John Spurlockaa5ee4d2014-07-25 13:05:12 -04003022 if (mMusicActiveMs == 0) {
3023 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE;
3024 enforceSafeMediaVolume();
3025 } else {
3026 // We have existing playback time recorded, already confirmed.
3027 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE;
3028 }
Eric Laurent05274f32012-11-29 12:48:18 -08003029 }
Eric Laurentd640bd32012-09-28 18:01:48 -07003030 } else {
Eric Laurent05274f32012-11-29 12:48:18 -08003031 persistedState = SAFE_MEDIA_VOLUME_DISABLED;
Eric Laurentd640bd32012-09-28 18:01:48 -07003032 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_DISABLED;
3033 }
3034 mMcc = mcc;
Eric Laurent05274f32012-11-29 12:48:18 -08003035 sendMsg(mAudioHandler,
3036 MSG_PERSIST_SAFE_VOLUME_STATE,
3037 SENDMSG_QUEUE,
3038 persistedState,
3039 0,
3040 null,
3041 0);
Eric Laurentd640bd32012-09-28 18:01:48 -07003042 }
3043 }
3044 }
3045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 ///////////////////////////////////////////////////////////////////////////
3047 // Internal methods
3048 ///////////////////////////////////////////////////////////////////////////
3049
3050 /**
3051 * Checks if the adjustment should change ringer mode instead of just
3052 * adjusting volume. If so, this will set the proper ringer mode and volume
3053 * indices on the stream states.
3054 */
RoboErik5452e252015-02-06 15:33:53 -08003055 private int checkForRingerModeChange(int oldIndex, int direction, int step, boolean isMuted) {
John Spurlocka11b4af2014-06-01 11:52:23 -04003056 int result = FLAG_ADJUST_VOLUME;
John Spurlock661f2cf2014-11-17 10:29:10 -05003057 int ringerMode = getRingerModeInternal();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058
Eric Laurentbffc3d12012-05-07 17:43:49 -07003059 switch (ringerMode) {
3060 case RINGER_MODE_NORMAL:
3061 if (direction == AudioManager.ADJUST_LOWER) {
3062 if (mHasVibrator) {
Eric Laurent24482012012-05-10 09:41:17 -07003063 // "step" is the delta in internal index units corresponding to a
3064 // change of 1 in UI index units.
3065 // Because of rounding when rescaling from one stream index range to its alias
3066 // index range, we cannot simply test oldIndex == step:
3067 // (step <= oldIndex < 2 * step) is equivalent to: (old UI index == 1)
3068 if (step <= oldIndex && oldIndex < 2 * step) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07003069 ringerMode = RINGER_MODE_VIBRATE;
3070 }
3071 } else {
Eric Laurent24482012012-05-10 09:41:17 -07003072 // (oldIndex < step) is equivalent to (old UI index == 0)
John Spurlock86005342014-05-23 11:58:00 -04003073 if ((oldIndex < step)
3074 && VOLUME_SETS_RINGER_MODE_SILENT
3075 && mPrevVolDirection != AudioManager.ADJUST_LOWER) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07003076 ringerMode = RINGER_MODE_SILENT;
3077 }
Eric Laurent3d4c06f2011-08-15 19:58:28 -07003078 }
RoboErik5452e252015-02-06 15:33:53 -08003079 } else if (direction == AudioManager.ADJUST_TOGGLE_MUTE
3080 || direction == AudioManager.ADJUST_MUTE) {
3081 if (mHasVibrator) {
3082 ringerMode = RINGER_MODE_VIBRATE;
3083 } else {
3084 ringerMode = RINGER_MODE_SILENT;
3085 }
3086 // Setting the ringer mode will toggle mute
3087 result &= ~FLAG_ADJUST_VOLUME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003089 break;
3090 case RINGER_MODE_VIBRATE:
3091 if (!mHasVibrator) {
3092 Log.e(TAG, "checkForRingerModeChange() current ringer mode is vibrate" +
3093 "but no vibrator is present");
3094 break;
3095 }
Amith Yamasanic696a532011-10-28 17:02:37 -07003096 if ((direction == AudioManager.ADJUST_LOWER)) {
RoboErik5452e252015-02-06 15:33:53 -08003097 // This is the case we were muted with the volume turned up
3098 if (oldIndex >= 2 * step && isMuted) {
3099 ringerMode = RINGER_MODE_NORMAL;
3100 } else if (mPrevVolDirection != AudioManager.ADJUST_LOWER) {
John Spurlock795a5142014-12-08 14:09:35 -05003101 if (VOLUME_SETS_RINGER_MODE_SILENT) {
3102 ringerMode = RINGER_MODE_SILENT;
3103 } else {
3104 result |= AudioManager.FLAG_SHOW_VIBRATE_HINT;
3105 }
Amith Yamasanic696a532011-10-28 17:02:37 -07003106 }
RoboErik5452e252015-02-06 15:33:53 -08003107 } else if (direction == AudioManager.ADJUST_RAISE
3108 || direction == AudioManager.ADJUST_TOGGLE_MUTE
3109 || direction == AudioManager.ADJUST_UNMUTE) {
Eric Laurentbffc3d12012-05-07 17:43:49 -07003110 ringerMode = RINGER_MODE_NORMAL;
Amith Yamasanic696a532011-10-28 17:02:37 -07003111 }
John Spurlocka11b4af2014-06-01 11:52:23 -04003112 result &= ~FLAG_ADJUST_VOLUME;
Eric Laurentbffc3d12012-05-07 17:43:49 -07003113 break;
3114 case RINGER_MODE_SILENT:
RoboErik5452e252015-02-06 15:33:53 -08003115 if (direction == AudioManager.ADJUST_LOWER && oldIndex >= 2 * step && isMuted) {
3116 // This is the case we were muted with the volume turned up
3117 ringerMode = RINGER_MODE_NORMAL;
3118 } else if (direction == AudioManager.ADJUST_RAISE
3119 || direction == AudioManager.ADJUST_TOGGLE_MUTE
3120 || direction == AudioManager.ADJUST_UNMUTE) {
John Spurlocka11b4af2014-06-01 11:52:23 -04003121 if (PREVENT_VOLUME_ADJUSTMENT_IF_SILENT) {
3122 result |= AudioManager.FLAG_SHOW_SILENT_HINT;
Eric Laurentbffc3d12012-05-07 17:43:49 -07003123 } else {
RoboErik5452e252015-02-06 15:33:53 -08003124 if (mHasVibrator && direction == AudioManager.ADJUST_RAISE) {
John Spurlocka11b4af2014-06-01 11:52:23 -04003125 ringerMode = RINGER_MODE_VIBRATE;
3126 } else {
RoboErik5452e252015-02-06 15:33:53 -08003127 // If we don't have a vibrator or they were toggling mute
3128 // go straight back to normal.
John Spurlocka11b4af2014-06-01 11:52:23 -04003129 ringerMode = RINGER_MODE_NORMAL;
3130 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003131 }
Daniel Sandler6329bf72010-02-26 15:17:44 -05003132 }
John Spurlocka11b4af2014-06-01 11:52:23 -04003133 result &= ~FLAG_ADJUST_VOLUME;
Eric Laurentbffc3d12012-05-07 17:43:49 -07003134 break;
3135 default:
3136 Log.e(TAG, "checkForRingerModeChange() wrong ringer mode: "+ringerMode);
3137 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 }
3139
John Spurlock661f2cf2014-11-17 10:29:10 -05003140 setRingerMode(ringerMode, TAG + ".checkForRingerModeChange", false /*external*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141
Eric Laurent25101b02011-02-02 09:33:30 -08003142 mPrevVolDirection = direction;
3143
John Spurlocka11b4af2014-06-01 11:52:23 -04003144 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
3146
John Spurlock3346a802014-05-20 16:25:37 -04003147 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 public boolean isStreamAffectedByRingerMode(int streamType) {
Eric Laurent9bcf4012009-06-12 06:09:28 -07003149 return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
3151
Eric Laurent5b4e6542010-03-19 20:02:21 -07003152 private boolean isStreamMutedByRingerMode(int streamType) {
3153 return (mRingerModeMutedStreams & (1 << streamType)) != 0;
3154 }
3155
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003156 boolean updateRingerModeAffectedStreams() {
3157 int ringerModeAffectedStreams;
3158 // make sure settings for ringer mode are consistent with device type: non voice capable
3159 // devices (tablets) include media stream in silent mode whereas phones don't.
3160 ringerModeAffectedStreams = Settings.System.getIntForUser(mContentResolver,
3161 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
3162 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
3163 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)),
3164 UserHandle.USER_CURRENT);
3165
3166 // ringtone, notification and system streams are always affected by ringer mode
3167 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_RING)|
3168 (1 << AudioSystem.STREAM_NOTIFICATION)|
3169 (1 << AudioSystem.STREAM_SYSTEM);
3170
Eric Laurent212532b2014-07-21 15:43:18 -07003171 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -05003172 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -07003173 ringerModeAffectedStreams = 0;
3174 break;
3175 default:
John Spurlock77e54d92014-08-11 12:16:24 -04003176 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
Eric Laurent212532b2014-07-21 15:43:18 -07003177 break;
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003178 }
Eric Laurent212532b2014-07-21 15:43:18 -07003179
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003180 synchronized (mCameraSoundForced) {
3181 if (mCameraSoundForced) {
3182 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
3183 } else {
3184 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
3185 }
3186 }
3187 if (mStreamVolumeAlias[AudioSystem.STREAM_DTMF] == AudioSystem.STREAM_RING) {
3188 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_DTMF);
3189 } else {
3190 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_DTMF);
3191 }
3192
3193 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
3194 Settings.System.putIntForUser(mContentResolver,
3195 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
3196 ringerModeAffectedStreams,
3197 UserHandle.USER_CURRENT);
3198 mRingerModeAffectedStreams = ringerModeAffectedStreams;
3199 return true;
3200 }
3201 return false;
3202 }
3203
John Spurlocka9dfbe8b2015-02-17 11:01:51 -05003204 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 public boolean isStreamAffectedByMute(int streamType) {
3206 return (mMuteAffectedStreams & (1 << streamType)) != 0;
3207 }
3208
3209 private void ensureValidDirection(int direction) {
RoboErik4197cb62015-01-21 15:45:32 -08003210 switch (direction) {
3211 case AudioManager.ADJUST_LOWER:
3212 case AudioManager.ADJUST_RAISE:
3213 case AudioManager.ADJUST_SAME:
3214 case AudioManager.ADJUST_MUTE:
3215 case AudioManager.ADJUST_UNMUTE:
3216 case AudioManager.ADJUST_TOGGLE_MUTE:
3217 break;
3218 default:
3219 throw new IllegalArgumentException("Bad direction " + direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
3221 }
3222
Lei Zhang6c798972012-03-02 11:40:12 -08003223 private void ensureValidSteps(int steps) {
3224 if (Math.abs(steps) > MAX_BATCH_VOLUME_ADJUST_STEPS) {
3225 throw new IllegalArgumentException("Bad volume adjust steps " + steps);
3226 }
3227 }
3228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 private void ensureValidStreamType(int streamType) {
3230 if (streamType < 0 || streamType >= mStreamStates.length) {
3231 throw new IllegalArgumentException("Bad stream type " + streamType);
3232 }
3233 }
3234
RoboErik4197cb62015-01-21 15:45:32 -08003235 private boolean isMuteAdjust(int adjust) {
3236 return adjust == AudioManager.ADJUST_MUTE || adjust == AudioManager.ADJUST_UNMUTE
3237 || adjust == AudioManager.ADJUST_TOGGLE_MUTE;
3238 }
3239
Eric Laurent6d517662012-04-23 18:42:39 -07003240 private boolean isInCommunication() {
Nancy Chen0eb1e402014-08-21 22:52:29 -07003241 boolean IsInCall = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242
Tyler Gunnef9f6f92014-09-12 22:16:17 -07003243 TelecomManager telecomManager =
3244 (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
Eric Laurent38edfda2014-12-18 17:38:04 -08003245
3246 final long ident = Binder.clearCallingIdentity();
Tyler Gunnef9f6f92014-09-12 22:16:17 -07003247 IsInCall = telecomManager.isInCall();
Eric Laurent38edfda2014-12-18 17:38:04 -08003248 Binder.restoreCallingIdentity(ident);
Santos Cordon9eb45932014-06-27 12:28:43 -07003249
Nancy Chen0eb1e402014-08-21 22:52:29 -07003250 return (IsInCall || getMode() == AudioManager.MODE_IN_COMMUNICATION);
Eric Laurent6d517662012-04-23 18:42:39 -07003251 }
Eric Laurent25101b02011-02-02 09:33:30 -08003252
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003253 /**
3254 * For code clarity for getActiveStreamType(int)
3255 * @param delay_ms max time since last STREAM_MUSIC activity to consider
3256 * @return true if STREAM_MUSIC is active in streams handled by AudioFlinger now or
3257 * in the last "delay_ms" ms.
3258 */
3259 private boolean isAfMusicActiveRecently(int delay_ms) {
3260 return AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, delay_ms)
3261 || AudioSystem.isStreamActiveRemotely(AudioSystem.STREAM_MUSIC, delay_ms);
3262 }
3263
Eric Laurent6d517662012-04-23 18:42:39 -07003264 private int getActiveStreamType(int suggestedStreamType) {
Eric Laurent212532b2014-07-21 15:43:18 -07003265 switch (mPlatformType) {
John Spurlock61560172015-02-06 19:46:04 -05003266 case AudioSystem.PLATFORM_VOICE:
Eric Laurent6d517662012-04-23 18:42:39 -07003267 if (isInCommunication()) {
Eric Laurent25101b02011-02-02 09:33:30 -08003268 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
3269 == AudioSystem.FORCE_BT_SCO) {
3270 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
3271 return AudioSystem.STREAM_BLUETOOTH_SCO;
3272 } else {
3273 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
3274 return AudioSystem.STREAM_VOICE_CALL;
3275 }
Eric Laurent25101b02011-02-02 09:33:30 -08003276 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003277 if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003278 if (DEBUG_VOL)
3279 Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
3280 return AudioSystem.STREAM_MUSIC;
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003281 } else {
3282 if (DEBUG_VOL)
3283 Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING b/c default");
3284 return AudioSystem.STREAM_RING;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003285 }
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003286 } else if (isAfMusicActiveRecently(0)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003287 if (DEBUG_VOL)
3288 Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
3289 return AudioSystem.STREAM_MUSIC;
Eric Laurent25101b02011-02-02 09:33:30 -08003290 }
Eric Laurent212532b2014-07-21 15:43:18 -07003291 break;
John Spurlock61560172015-02-06 19:46:04 -05003292 case AudioSystem.PLATFORM_TELEVISION:
Eric Laurent212532b2014-07-21 15:43:18 -07003293 if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
RoboErik2811dd32014-08-12 09:48:13 -07003294 // TV always defaults to STREAM_MUSIC
Eric Laurent212532b2014-07-21 15:43:18 -07003295 return AudioSystem.STREAM_MUSIC;
Eric Laurent212532b2014-07-21 15:43:18 -07003296 }
3297 break;
3298 default:
Eric Laurent6d517662012-04-23 18:42:39 -07003299 if (isInCommunication()) {
Eric Laurent25101b02011-02-02 09:33:30 -08003300 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
3301 == AudioSystem.FORCE_BT_SCO) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003302 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO");
Eric Laurent25101b02011-02-02 09:33:30 -08003303 return AudioSystem.STREAM_BLUETOOTH_SCO;
3304 } else {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003305 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL");
Eric Laurent25101b02011-02-02 09:33:30 -08003306 return AudioSystem.STREAM_VOICE_CALL;
3307 }
3308 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003309 StreamOverride.sDelayMs) ||
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003310 AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003311 StreamOverride.sDelayMs)) {
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003312 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION");
Eric Laurent25101b02011-02-02 09:33:30 -08003313 return AudioSystem.STREAM_NOTIFICATION;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003314 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07003315 if (isAfMusicActiveRecently(StreamOverride.sDelayMs)) {
Jean-Michel Trivifca1e602013-10-10 18:12:59 -07003316 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: forcing STREAM_MUSIC");
3317 return AudioSystem.STREAM_MUSIC;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003318 } else {
John Spurlockeb1d88d2014-07-19 14:49:19 -04003319 if (DEBUG_VOL) Log.v(TAG,
3320 "getActiveStreamType: using STREAM_NOTIFICATION as default");
3321 return AudioSystem.STREAM_NOTIFICATION;
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07003322 }
Joe Onoratoc7fcba42011-01-05 16:53:11 -08003323 }
Eric Laurent212532b2014-07-21 15:43:18 -07003324 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 }
Eric Laurent212532b2014-07-21 15:43:18 -07003326 if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Returning suggested type "
3327 + suggestedStreamType);
3328 return suggestedStreamType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330
John Spurlockbcc10872014-11-28 15:29:21 -05003331 private void broadcastRingerMode(String action, int ringerMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 // Send sticky broadcast
John Spurlockbcc10872014-11-28 15:29:21 -05003333 Intent broadcast = new Intent(action);
Glenn Kastenba195eb2011-12-13 09:30:40 -08003334 broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, ringerMode);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08003335 broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
3336 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003337 sendStickyBroadcastToAll(broadcast);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
3339
3340 private void broadcastVibrateSetting(int vibrateType) {
3341 // Send broadcast
3342 if (ActivityManagerNative.isSystemReady()) {
3343 Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
3344 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
3345 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003346 sendBroadcastToAll(broadcast);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 }
3348 }
3349
3350 // Message helper methods
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003351 /**
3352 * Queue a message on the given handler's message queue, after acquiring the service wake lock.
3353 * Note that the wake lock needs to be released after the message has been handled.
3354 */
3355 private void queueMsgUnderWakeLock(Handler handler, int msg,
3356 int arg1, int arg2, Object obj, int delay) {
Eric Laurenta4dfbdc52013-10-01 11:53:51 -07003357 final long ident = Binder.clearCallingIdentity();
3358 // Always acquire the wake lock as AudioService because it is released by the
3359 // message handler.
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07003360 mAudioEventWakeLock.acquire();
Eric Laurenta4dfbdc52013-10-01 11:53:51 -07003361 Binder.restoreCallingIdentity(ident);
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003362 sendMsg(handler, msg, SENDMSG_QUEUE, arg1, arg2, obj, delay);
3363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364
Eric Laurentafbb0472011-12-15 09:04:23 -08003365 private static void sendMsg(Handler handler, int msg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367
3368 if (existingMsgPolicy == SENDMSG_REPLACE) {
3369 handler.removeMessages(msg);
3370 } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
3371 return;
3372 }
Eric Laurentadbe8bf2014-11-03 18:26:32 -08003373 synchronized (mLastDeviceConnectMsgTime) {
3374 long time = SystemClock.uptimeMillis() + delay;
3375 handler.sendMessageAtTime(handler.obtainMessage(msg, arg1, arg2, obj), time);
3376 if (msg == MSG_SET_WIRED_DEVICE_CONNECTION_STATE ||
3377 msg == MSG_SET_A2DP_SRC_CONNECTION_STATE ||
3378 msg == MSG_SET_A2DP_SINK_CONNECTION_STATE) {
3379 mLastDeviceConnectMsgTime = time;
3380 }
3381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 }
3383
3384 boolean checkAudioSettingsPermission(String method) {
Jean-Michel Triviccd654e2014-09-03 17:48:47 -07003385 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 == PackageManager.PERMISSION_GRANTED) {
3387 return true;
3388 }
3389 String msg = "Audio Settings Permission Denial: " + method + " from pid="
3390 + Binder.getCallingPid()
3391 + ", uid=" + Binder.getCallingUid();
3392 Log.w(TAG, msg);
3393 return false;
3394 }
3395
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003396 private int getDeviceForStream(int stream) {
3397 int device = AudioSystem.getDevicesForStream(stream);
3398 if ((device & (device - 1)) != 0) {
3399 // Multiple device selection is either:
3400 // - speaker + one other device: give priority to speaker in this case.
3401 // - one A2DP device + another device: happens with duplicated output. In this case
3402 // retain the device on the A2DP output as the other must not correspond to an active
3403 // selection if not the speaker.
Jungshik Jangc9ff9682014-09-15 17:41:06 +09003404 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003405 if ((device & AudioSystem.DEVICE_OUT_SPEAKER) != 0) {
3406 device = AudioSystem.DEVICE_OUT_SPEAKER;
Jungshik Jangc9ff9682014-09-15 17:41:06 +09003407 } else if ((device & AudioSystem.DEVICE_OUT_HDMI_ARC) != 0) {
3408 device = AudioSystem.DEVICE_OUT_HDMI_ARC;
3409 } else if ((device & AudioSystem.DEVICE_OUT_SPDIF) != 0) {
3410 device = AudioSystem.DEVICE_OUT_SPDIF;
3411 } else if ((device & AudioSystem.DEVICE_OUT_AUX_LINE) != 0) {
3412 device = AudioSystem.DEVICE_OUT_AUX_LINE;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003413 } else {
3414 device &= AudioSystem.DEVICE_OUT_ALL_A2DP;
3415 }
3416 }
3417 return device;
3418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419
Paul McLean10804eb2015-01-28 11:16:35 -08003420 /*
3421 * A class just for packaging up a set of connection parameters.
3422 */
3423 private class WiredDeviceConnectionState {
3424 public int mType;
3425 public int mState;
3426 public String mAddress;
3427 public String mName;
3428
3429 public WiredDeviceConnectionState(int type, int state, String address, String name) {
3430 mType = type;
3431 mState = state;
3432 mAddress = address;
3433 mName = name;
3434 }
3435 }
3436
3437 public void setWiredDeviceConnectionState(int type, int state, String address,
3438 String name) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003439 synchronized (mConnectedDevices) {
Paul McLean10804eb2015-01-28 11:16:35 -08003440 int delay = checkSendBecomingNoisyIntent(type, state);
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003441 queueMsgUnderWakeLock(mAudioHandler,
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003442 MSG_SET_WIRED_DEVICE_CONNECTION_STATE,
Paul McLean10804eb2015-01-28 11:16:35 -08003443 0,
3444 0,
3445 new WiredDeviceConnectionState(type, state, address, name),
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003446 delay);
3447 }
3448 }
3449
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003450 public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state, int profile)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003451 {
3452 int delay;
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003453 if (profile != BluetoothProfile.A2DP && profile != BluetoothProfile.A2DP_SINK) {
3454 throw new IllegalArgumentException("invalid profile " + profile);
3455 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003456 synchronized (mConnectedDevices) {
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003457 if (profile == BluetoothProfile.A2DP) {
3458 delay = checkSendBecomingNoisyIntent(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
3459 (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
3460 } else {
3461 delay = 0;
3462 }
Jean-Michel Trivi2d8dab52012-05-30 18:13:59 -07003463 queueMsgUnderWakeLock(mAudioHandler,
Mike Lockwood0a40ec22014-05-21 10:08:50 -07003464 (profile == BluetoothProfile.A2DP ?
3465 MSG_SET_A2DP_SINK_CONNECTION_STATE : MSG_SET_A2DP_SRC_CONNECTION_STATE),
Eric Laurentb1fbaac2012-05-29 09:24:28 -07003466 state,
3467 0,
3468 device,
3469 delay);
3470 }
3471 return delay;
3472 }
3473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 ///////////////////////////////////////////////////////////////////////////
3475 // Inner classes
3476 ///////////////////////////////////////////////////////////////////////////
3477
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003478 // NOTE: Locking order for synchronized objects related to volume or ringer mode management:
3479 // 1 mScoclient OR mSafeMediaVolumeState
3480 // 2 mSetModeDeathHandlers
3481 // 3 mSettingsLock
3482 // 4 VolumeStreamState.class
3483 // 5 mCameraSoundForced
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 public class VolumeStreamState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 private final int mStreamType;
3486
RoboErik4197cb62015-01-21 15:45:32 -08003487 private boolean mIsMuted;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07003488 private String mVolumeIndexSettingName;
Eric Laurenta553c252009-07-17 12:17:14 -07003489 private int mIndexMax;
Eric Laurent3172d5e2012-05-09 11:38:16 -07003490 private final ConcurrentHashMap<Integer, Integer> mIndex =
3491 new ConcurrentHashMap<Integer, Integer>(8, 0.75f, 4);
John Spurlockf63860c2015-02-19 09:46:27 -05003492 private final Intent mVolumeChanged;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493
Eric Laurenta553c252009-07-17 12:17:14 -07003494 private VolumeStreamState(String settingName, int streamType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003496 mVolumeIndexSettingName = settingName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497
3498 mStreamType = streamType;
Jared Suttles59820132009-08-13 21:50:52 -05003499 mIndexMax = MAX_STREAM_VOLUME[streamType];
Eric Laurenta553c252009-07-17 12:17:14 -07003500 AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
3501 mIndexMax *= 10;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003502
Eric Laurent33902db2012-10-07 16:15:07 -07003503 readSettings();
John Spurlockf63860c2015-02-19 09:46:27 -05003504 mVolumeChanged = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
3505 mVolumeChanged.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, mStreamType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 }
3507
Eric Laurent42b041e2013-03-29 11:36:03 -07003508 public String getSettingNameForDevice(int device) {
3509 String name = mVolumeIndexSettingName;
Eric Laurent948d3272014-05-16 15:18:45 -07003510 String suffix = AudioSystem.getOutputDeviceName(device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003511 if (suffix.isEmpty()) {
3512 return name;
3513 }
3514 return name + "_" + suffix;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07003515 }
3516
Eric Laurentfdbee862014-05-12 15:26:12 -07003517 public void readSettings() {
3518 synchronized (VolumeStreamState.class) {
Wally Yauda392902014-11-28 12:40:30 -08003519 // force maximum volume on all streams if fixed volume property
3520 // or master volume property is set
3521 if (mUseFixedVolume || mUseMasterVolume) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003522 mIndex.put(AudioSystem.DEVICE_OUT_DEFAULT, mIndexMax);
3523 return;
3524 }
3525 // do not read system stream volume from settings: this stream is always aliased
3526 // to another stream type and its volume is never persisted. Values in settings can
3527 // only be stale values
3528 if ((mStreamType == AudioSystem.STREAM_SYSTEM) ||
3529 (mStreamType == AudioSystem.STREAM_SYSTEM_ENFORCED)) {
John Spurlock61560172015-02-06 19:46:04 -05003530 int index = 10 * AudioSystem.DEFAULT_STREAM_VOLUME[mStreamType];
Eric Laurentfdbee862014-05-12 15:26:12 -07003531 synchronized (mCameraSoundForced) {
3532 if (mCameraSoundForced) {
3533 index = mIndexMax;
3534 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003535 }
Eric Laurentfdbee862014-05-12 15:26:12 -07003536 mIndex.put(AudioSystem.DEVICE_OUT_DEFAULT, index);
3537 return;
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003538 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003539
Eric Laurentfdbee862014-05-12 15:26:12 -07003540 int remainingDevices = AudioSystem.DEVICE_OUT_ALL;
3541
3542 for (int i = 0; remainingDevices != 0; i++) {
3543 int device = (1 << i);
3544 if ((device & remainingDevices) == 0) {
3545 continue;
3546 }
3547 remainingDevices &= ~device;
3548
3549 // retrieve current volume for device
3550 String name = getSettingNameForDevice(device);
3551 // if no volume stored for current stream and device, use default volume if default
3552 // device, continue otherwise
3553 int defaultIndex = (device == AudioSystem.DEVICE_OUT_DEFAULT) ?
John Spurlock61560172015-02-06 19:46:04 -05003554 AudioSystem.DEFAULT_STREAM_VOLUME[mStreamType] : -1;
Eric Laurentfdbee862014-05-12 15:26:12 -07003555 int index = Settings.System.getIntForUser(
3556 mContentResolver, name, defaultIndex, UserHandle.USER_CURRENT);
3557 if (index == -1) {
3558 continue;
3559 }
3560
Eric Laurent212532b2014-07-21 15:43:18 -07003561 mIndex.put(device, getValidIndex(10 * index));
Eric Laurentdd45d012012-10-08 09:04:34 -07003562 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 }
3565
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003566 // must be called while synchronized VolumeStreamState.class
3567 public void applyDeviceVolume_syncVSS(int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003568 int index;
RoboErik4197cb62015-01-21 15:45:32 -08003569 if (mIsMuted) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003570 index = 0;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003571 } else if (((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 && mAvrcpAbsVolSupported)
3572 || ((device & mFullVolumeDevices) != 0)) {
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07003573 index = (mIndexMax + 5)/10;
Eric Laurentcd772d02013-10-30 18:31:07 -07003574 } else {
Eric Laurent42b041e2013-03-29 11:36:03 -07003575 index = (getIndex(device) + 5)/10;
3576 }
3577 AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579
Eric Laurentfdbee862014-05-12 15:26:12 -07003580 public void applyAllVolumes() {
3581 synchronized (VolumeStreamState.class) {
3582 // apply default volume first: by convention this will reset all
3583 // devices volumes in audio policy manager to the supplied value
3584 int index;
RoboErik4197cb62015-01-21 15:45:32 -08003585 if (mIsMuted) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003586 index = 0;
3587 } else {
3588 index = (getIndex(AudioSystem.DEVICE_OUT_DEFAULT) + 5)/10;
3589 }
3590 AudioSystem.setStreamVolumeIndex(mStreamType, index, AudioSystem.DEVICE_OUT_DEFAULT);
3591 // then apply device specific volumes
3592 Set set = mIndex.entrySet();
3593 Iterator i = set.iterator();
3594 while (i.hasNext()) {
3595 Map.Entry entry = (Map.Entry)i.next();
3596 int device = ((Integer)entry.getKey()).intValue();
3597 if (device != AudioSystem.DEVICE_OUT_DEFAULT) {
RoboErik4197cb62015-01-21 15:45:32 -08003598 if (mIsMuted) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003599 index = 0;
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003600 } else if (((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
3601 mAvrcpAbsVolSupported)
3602 || ((device & mFullVolumeDevices) != 0))
3603 {
Eric Laurentfdbee862014-05-12 15:26:12 -07003604 index = (mIndexMax + 5)/10;
3605 } else {
3606 index = ((Integer)entry.getValue() + 5)/10;
3607 }
3608 AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
Eric Laurent42b041e2013-03-29 11:36:03 -07003609 }
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003610 }
3611 }
3612 }
3613
3614 public boolean adjustIndex(int deltaIndex, int device) {
Eric Laurent42b041e2013-03-29 11:36:03 -07003615 return setIndex(getIndex(device) + deltaIndex,
3616 device);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003617 }
3618
Eric Laurentfdbee862014-05-12 15:26:12 -07003619 public boolean setIndex(int index, int device) {
John Spurlockf63860c2015-02-19 09:46:27 -05003620 boolean changed = false;
3621 int oldIndex;
Eric Laurentfdbee862014-05-12 15:26:12 -07003622 synchronized (VolumeStreamState.class) {
John Spurlockf63860c2015-02-19 09:46:27 -05003623 oldIndex = getIndex(device);
Eric Laurentfdbee862014-05-12 15:26:12 -07003624 index = getValidIndex(index);
3625 synchronized (mCameraSoundForced) {
3626 if ((mStreamType == AudioSystem.STREAM_SYSTEM_ENFORCED) && mCameraSoundForced) {
3627 index = mIndexMax;
Eric Laurenta553c252009-07-17 12:17:14 -07003628 }
3629 }
Eric Laurentfdbee862014-05-12 15:26:12 -07003630 mIndex.put(device, index);
3631
John Spurlockf63860c2015-02-19 09:46:27 -05003632 changed = oldIndex != index;
3633 if (changed) {
Eric Laurentfdbee862014-05-12 15:26:12 -07003634 // Apply change to all streams using this one as alias
3635 // if changing volume of current device, also change volume of current
3636 // device on aliased stream
3637 boolean currentDevice = (device == getDeviceForStream(mStreamType));
3638 int numStreamTypes = AudioSystem.getNumStreamTypes();
3639 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3640 if (streamType != mStreamType &&
3641 mStreamVolumeAlias[streamType] == mStreamType) {
3642 int scaledIndex = rescaleIndex(index, mStreamType, streamType);
3643 mStreamStates[streamType].setIndex(scaledIndex,
3644 device);
3645 if (currentDevice) {
3646 mStreamStates[streamType].setIndex(scaledIndex,
3647 getDeviceForStream(streamType));
3648 }
3649 }
3650 }
Eric Laurentfdbee862014-05-12 15:26:12 -07003651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 }
John Spurlockf63860c2015-02-19 09:46:27 -05003653 if (changed) {
3654 oldIndex = (oldIndex + 5) / 10;
3655 index = (index + 5) / 10;
3656 mVolumeChanged.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
3657 mVolumeChanged.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
3658 sendBroadcastToAll(mVolumeChanged);
3659 }
3660 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 }
3662
Eric Laurentfdbee862014-05-12 15:26:12 -07003663 public int getIndex(int device) {
3664 synchronized (VolumeStreamState.class) {
3665 Integer index = mIndex.get(device);
3666 if (index == null) {
3667 // there is always an entry for AudioSystem.DEVICE_OUT_DEFAULT
3668 index = mIndex.get(AudioSystem.DEVICE_OUT_DEFAULT);
3669 }
3670 return index.intValue();
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003671 }
Eric Laurent5b4e6542010-03-19 20:02:21 -07003672 }
3673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 public int getMaxIndex() {
Eric Laurenta553c252009-07-17 12:17:14 -07003675 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 }
3677
Eric Laurentfdbee862014-05-12 15:26:12 -07003678 public void setAllIndexes(VolumeStreamState srcStream) {
3679 synchronized (VolumeStreamState.class) {
3680 int srcStreamType = srcStream.getStreamType();
3681 // apply default device volume from source stream to all devices first in case
3682 // some devices are present in this stream state but not in source stream state
3683 int index = srcStream.getIndex(AudioSystem.DEVICE_OUT_DEFAULT);
Eric Laurent24e0d9b2013-10-03 18:15:07 -07003684 index = rescaleIndex(index, srcStreamType, mStreamType);
Eric Laurentfdbee862014-05-12 15:26:12 -07003685 Set set = mIndex.entrySet();
3686 Iterator i = set.iterator();
3687 while (i.hasNext()) {
3688 Map.Entry entry = (Map.Entry)i.next();
3689 entry.setValue(index);
3690 }
3691 // Now apply actual volume for devices in source stream state
3692 set = srcStream.mIndex.entrySet();
3693 i = set.iterator();
3694 while (i.hasNext()) {
3695 Map.Entry entry = (Map.Entry)i.next();
3696 int device = ((Integer)entry.getKey()).intValue();
3697 index = ((Integer)entry.getValue()).intValue();
3698 index = rescaleIndex(index, srcStreamType, mStreamType);
Eric Laurent33902db2012-10-07 16:15:07 -07003699
Eric Laurentfdbee862014-05-12 15:26:12 -07003700 setIndex(index, device);
3701 }
Eric Laurent6d517662012-04-23 18:42:39 -07003702 }
3703 }
3704
Eric Laurentfdbee862014-05-12 15:26:12 -07003705 public void setAllIndexesToMax() {
3706 synchronized (VolumeStreamState.class) {
3707 Set set = mIndex.entrySet();
3708 Iterator i = set.iterator();
3709 while (i.hasNext()) {
3710 Map.Entry entry = (Map.Entry)i.next();
3711 entry.setValue(mIndexMax);
3712 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003713 }
Eric Laurentdd45d012012-10-08 09:04:34 -07003714 }
3715
RoboErik4197cb62015-01-21 15:45:32 -08003716 public void mute(boolean state) {
John Spurlock22b9ee12015-02-18 22:51:44 -05003717 boolean changed = false;
Eric Laurentfdbee862014-05-12 15:26:12 -07003718 synchronized (VolumeStreamState.class) {
RoboErik4197cb62015-01-21 15:45:32 -08003719 if (state != mIsMuted) {
John Spurlock22b9ee12015-02-18 22:51:44 -05003720 changed = true;
RoboErik4197cb62015-01-21 15:45:32 -08003721 mIsMuted = state;
John Spurlock22b9ee12015-02-18 22:51:44 -05003722
RoboErik4197cb62015-01-21 15:45:32 -08003723 // Set the new mute volume. This propagates the values to
3724 // the audio system, otherwise the volume won't be changed
3725 // at the lower level.
3726 sendMsg(mAudioHandler,
3727 MSG_SET_ALL_VOLUMES,
3728 SENDMSG_QUEUE,
3729 0,
3730 0,
3731 this, 0);
Eric Laurentfdbee862014-05-12 15:26:12 -07003732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 }
John Spurlock22b9ee12015-02-18 22:51:44 -05003734 if (changed) {
3735 // Stream mute changed, fire the intent.
3736 Intent intent = new Intent(AudioManager.STREAM_MUTE_CHANGED_ACTION);
3737 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, mStreamType);
3738 intent.putExtra(AudioManager.EXTRA_STREAM_VOLUME_MUTED, state);
3739 sendBroadcastToAll(intent);
3740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 }
3742
Eric Laurent6d517662012-04-23 18:42:39 -07003743 public int getStreamType() {
3744 return mStreamType;
3745 }
3746
Eric Laurent212532b2014-07-21 15:43:18 -07003747 public void checkFixedVolumeDevices() {
3748 synchronized (VolumeStreamState.class) {
3749 // ignore settings for fixed volume devices: volume should always be at max or 0
3750 if (mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_MUSIC) {
3751 Set set = mIndex.entrySet();
3752 Iterator i = set.iterator();
3753 while (i.hasNext()) {
3754 Map.Entry entry = (Map.Entry)i.next();
3755 int device = ((Integer)entry.getKey()).intValue();
3756 int index = ((Integer)entry.getValue()).intValue();
Jean-Michel Triviba5270b2014-10-01 17:49:29 -07003757 if (((device & mFullVolumeDevices) != 0)
3758 || (((device & mFixedVolumeDevices) != 0) && index != 0)) {
Eric Laurent212532b2014-07-21 15:43:18 -07003759 entry.setValue(mIndexMax);
3760 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003761 applyDeviceVolume_syncVSS(device);
Eric Laurent212532b2014-07-21 15:43:18 -07003762 }
3763 }
3764 }
3765 }
3766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 private int getValidIndex(int index) {
3768 if (index < 0) {
3769 return 0;
Wally Yauda392902014-11-28 12:40:30 -08003770 } else if (mUseFixedVolume || mUseMasterVolume || index > mIndexMax) {
Eric Laurenta553c252009-07-17 12:17:14 -07003771 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 }
3773
3774 return index;
3775 }
3776
Eric Laurentbffc3d12012-05-07 17:43:49 -07003777 private void dump(PrintWriter pw) {
RoboErik4197cb62015-01-21 15:45:32 -08003778 pw.print(" Muted: ");
3779 pw.println(mIsMuted);
John Spurlock2b29bc42014-08-26 16:40:35 -04003780 pw.print(" Max: ");
3781 pw.println((mIndexMax + 5) / 10);
Eric Laurentbffc3d12012-05-07 17:43:49 -07003782 pw.print(" Current: ");
3783 Set set = mIndex.entrySet();
3784 Iterator i = set.iterator();
3785 while (i.hasNext()) {
3786 Map.Entry entry = (Map.Entry)i.next();
John Spurlock2b29bc42014-08-26 16:40:35 -04003787 final int device = (Integer) entry.getKey();
3788 pw.print(Integer.toHexString(device));
3789 final String deviceName = device == AudioSystem.DEVICE_OUT_DEFAULT ? "default"
3790 : AudioSystem.getOutputDeviceName(device);
3791 if (!deviceName.isEmpty()) {
3792 pw.print(" (");
3793 pw.print(deviceName);
3794 pw.print(")");
3795 }
3796 pw.print(": ");
3797 final int index = (((Integer) entry.getValue()) + 5) / 10;
3798 pw.print(index);
3799 if (i.hasNext()) {
3800 pw.print(", ");
3801 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003802 }
Eric Laurentbffc3d12012-05-07 17:43:49 -07003803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 }
3805
3806 /** Thread that handles native AudioSystem control. */
3807 private class AudioSystemThread extends Thread {
3808 AudioSystemThread() {
3809 super("AudioService");
3810 }
3811
3812 @Override
3813 public void run() {
3814 // Set this thread up so the handler will work on it
3815 Looper.prepare();
3816
3817 synchronized(AudioService.this) {
3818 mAudioHandler = new AudioHandler();
3819
3820 // Notify that the handler has been created
3821 AudioService.this.notify();
3822 }
3823
3824 // Listen for volume change requests that are set by VolumePanel
3825 Looper.loop();
3826 }
3827 }
3828
3829 /** Handles internal volume messages in separate volume thread. */
3830 private class AudioHandler extends Handler {
3831
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003832 private void setDeviceVolume(VolumeStreamState streamState, int device) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003834 synchronized (VolumeStreamState.class) {
3835 // Apply volume
3836 streamState.applyDeviceVolume_syncVSS(device);
Eric Laurenta553c252009-07-17 12:17:14 -07003837
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07003838 // Apply change to all streams using this one as alias
3839 int numStreamTypes = AudioSystem.getNumStreamTypes();
3840 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3841 if (streamType != streamState.mStreamType &&
3842 mStreamVolumeAlias[streamType] == streamState.mStreamType) {
3843 // Make sure volume is also maxed out on A2DP device for aliased stream
3844 // that may have a different device selected
3845 int streamDevice = getDeviceForStream(streamType);
3846 if ((device != streamDevice) && mAvrcpAbsVolSupported &&
3847 ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0)) {
3848 mStreamStates[streamType].applyDeviceVolume_syncVSS(device);
3849 }
3850 mStreamStates[streamType].applyDeviceVolume_syncVSS(streamDevice);
Eric Laurentcd772d02013-10-30 18:31:07 -07003851 }
Eric Laurenta553c252009-07-17 12:17:14 -07003852 }
3853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 // Post a persist volume msg
Eric Laurentafbb0472011-12-15 09:04:23 -08003855 sendMsg(mAudioHandler,
3856 MSG_PERSIST_VOLUME,
Eric Laurent98ad9b92012-02-15 17:21:37 -08003857 SENDMSG_QUEUE,
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003858 device,
Eric Laurent42b041e2013-03-29 11:36:03 -07003859 0,
Eric Laurentafbb0472011-12-15 09:04:23 -08003860 streamState,
3861 PERSIST_DELAY);
3862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 }
3864
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003865 private void setAllVolumes(VolumeStreamState streamState) {
3866
3867 // Apply volume
3868 streamState.applyAllVolumes();
3869
3870 // Apply change to all streams using this one as alias
3871 int numStreamTypes = AudioSystem.getNumStreamTypes();
3872 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
3873 if (streamType != streamState.mStreamType &&
Eric Laurent6d517662012-04-23 18:42:39 -07003874 mStreamVolumeAlias[streamType] == streamState.mStreamType) {
Eric Laurent9bc8358d2011-11-18 16:43:31 -08003875 mStreamStates[streamType].applyAllVolumes();
3876 }
3877 }
3878 }
3879
Eric Laurent42b041e2013-03-29 11:36:03 -07003880 private void persistVolume(VolumeStreamState streamState, int device) {
Eric Laurent83a017b2013-03-19 18:15:31 -07003881 if (mUseFixedVolume) {
3882 return;
3883 }
Eric Laurent212532b2014-07-21 15:43:18 -07003884 if (isPlatformTelevision() && (streamState.mStreamType != AudioSystem.STREAM_MUSIC)) {
3885 return;
3886 }
Eric Laurent42b041e2013-03-29 11:36:03 -07003887 System.putIntForUser(mContentResolver,
3888 streamState.getSettingNameForDevice(device),
3889 (streamState.getIndex(device) + 5)/ 10,
3890 UserHandle.USER_CURRENT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
3892
Glenn Kastenba195eb2011-12-13 09:30:40 -08003893 private void persistRingerMode(int ringerMode) {
Eric Laurent83a017b2013-03-19 18:15:31 -07003894 if (mUseFixedVolume) {
3895 return;
3896 }
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07003897 Settings.Global.putInt(mContentResolver, Settings.Global.MODE_RINGER, ringerMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 }
3899
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003900 private boolean onLoadSoundEffects() {
3901 int status;
3902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 synchronized (mSoundEffectsLock) {
Eric Laurent4a5eeb92014-05-06 10:49:04 -07003904 if (!mSystemReady) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003905 Log.w(TAG, "onLoadSoundEffects() called before boot complete");
3906 return false;
3907 }
3908
3909 if (mSoundPool != null) {
3910 return true;
3911 }
3912
3913 loadTouchSoundAssets();
3914
Jean-Michel Trivi55a30c42014-07-20 17:56:11 -07003915 mSoundPool = new SoundPool.Builder()
3916 .setMaxStreams(NUM_SOUNDPOOL_CHANNELS)
3917 .setAudioAttributes(new AudioAttributes.Builder()
3918 .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
3919 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
3920 .build())
3921 .build();
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003922 mSoundPoolCallBack = null;
3923 mSoundPoolListenerThread = new SoundPoolListenerThread();
3924 mSoundPoolListenerThread.start();
3925 int attempts = 3;
3926 while ((mSoundPoolCallBack == null) && (attempts-- > 0)) {
3927 try {
3928 // Wait for mSoundPoolCallBack to be set by the other thread
Glenn Kasten167d1a22013-07-23 16:24:41 -07003929 mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003930 } catch (InterruptedException e) {
3931 Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
3932 }
3933 }
3934
3935 if (mSoundPoolCallBack == null) {
3936 Log.w(TAG, "onLoadSoundEffects() SoundPool listener or thread creation error");
3937 if (mSoundPoolLooper != null) {
3938 mSoundPoolLooper.quit();
3939 mSoundPoolLooper = null;
3940 }
3941 mSoundPoolListenerThread = null;
3942 mSoundPool.release();
3943 mSoundPool = null;
3944 return false;
3945 }
3946 /*
3947 * poolId table: The value -1 in this table indicates that corresponding
3948 * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
3949 * Once loaded, the value in poolId is the sample ID and the same
3950 * sample can be reused for another effect using the same file.
3951 */
3952 int[] poolId = new int[SOUND_EFFECT_FILES.size()];
3953 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.size(); fileIdx++) {
3954 poolId[fileIdx] = -1;
3955 }
3956 /*
3957 * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
3958 * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
3959 * this indicates we have a valid sample loaded for this effect.
3960 */
3961
3962 int numSamples = 0;
3963 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
3964 // Do not load sample if this effect uses the MediaPlayer
3965 if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
3966 continue;
3967 }
3968 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
3969 String filePath = Environment.getRootDirectory()
3970 + SOUND_EFFECTS_PATH
3971 + SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effect][0]);
3972 int sampleId = mSoundPool.load(filePath, 0);
3973 if (sampleId <= 0) {
3974 Log.w(TAG, "Soundpool could not load file: "+filePath);
3975 } else {
3976 SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
3977 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
3978 numSamples++;
3979 }
3980 } else {
3981 SOUND_EFFECT_FILES_MAP[effect][1] =
3982 poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
3983 }
3984 }
3985 // wait for all samples to be loaded
3986 if (numSamples > 0) {
3987 mSoundPoolCallBack.setSamples(poolId);
3988
3989 attempts = 3;
3990 status = 1;
3991 while ((status == 1) && (attempts-- > 0)) {
3992 try {
Glenn Kasten167d1a22013-07-23 16:24:41 -07003993 mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07003994 status = mSoundPoolCallBack.status();
3995 } catch (InterruptedException e) {
3996 Log.w(TAG, "Interrupted while waiting sound pool callback.");
3997 }
3998 }
3999 } else {
4000 status = -1;
4001 }
4002
4003 if (mSoundPoolLooper != null) {
4004 mSoundPoolLooper.quit();
4005 mSoundPoolLooper = null;
4006 }
4007 mSoundPoolListenerThread = null;
4008 if (status != 0) {
4009 Log.w(TAG,
4010 "onLoadSoundEffects(), Error "+status+ " while loading samples");
4011 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
4012 if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) {
4013 SOUND_EFFECT_FILES_MAP[effect][1] = -1;
4014 }
4015 }
4016
4017 mSoundPool.release();
4018 mSoundPool = null;
4019 }
4020 }
4021 return (status == 0);
4022 }
4023
4024 /**
4025 * Unloads samples from the sound pool.
4026 * This method can be called to free some memory when
4027 * sound effects are disabled.
4028 */
4029 private void onUnloadSoundEffects() {
4030 synchronized (mSoundEffectsLock) {
4031 if (mSoundPool == null) {
4032 return;
4033 }
4034
4035 int[] poolId = new int[SOUND_EFFECT_FILES.size()];
4036 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.size(); fileIdx++) {
4037 poolId[fileIdx] = 0;
4038 }
4039
4040 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
4041 if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
4042 continue;
4043 }
4044 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
4045 mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
4046 SOUND_EFFECT_FILES_MAP[effect][1] = -1;
4047 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
4048 }
4049 }
4050 mSoundPool.release();
4051 mSoundPool = null;
4052 }
4053 }
4054
4055 private void onPlaySoundEffect(int effectType, int volume) {
4056 synchronized (mSoundEffectsLock) {
4057
4058 onLoadSoundEffects();
4059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 if (mSoundPool == null) {
4061 return;
4062 }
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004063 float volFloat;
Eric Laurent25101b02011-02-02 09:33:30 -08004064 // use default if volume is not specified by caller
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004065 if (volume < 0) {
Jean-Michel Trivif2b0c112012-07-09 11:59:11 -07004066 volFloat = (float)Math.pow(10, (float)sSoundEffectVolumeDb/20);
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004067 } else {
RoboErik8a2cfc32014-05-16 11:19:38 -07004068 volFloat = volume / 1000.0f;
Eric Laurenta2ef57d2009-09-28 04:46:10 -07004069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070
4071 if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004072 mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1],
4073 volFloat, volFloat, 0, 0, 1.0f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 } else {
4075 MediaPlayer mediaPlayer = new MediaPlayer();
Glenn Kasten62b9aec2011-11-07 11:10:16 -08004076 try {
Eric Laurente78fced2013-03-15 16:03:47 -07004077 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH +
4078 SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effectType][0]);
Glenn Kasten62b9aec2011-11-07 11:10:16 -08004079 mediaPlayer.setDataSource(filePath);
4080 mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
4081 mediaPlayer.prepare();
Glenn Kasten068225d2012-02-27 16:21:04 -08004082 mediaPlayer.setVolume(volFloat);
Glenn Kasten62b9aec2011-11-07 11:10:16 -08004083 mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
4084 public void onCompletion(MediaPlayer mp) {
4085 cleanupPlayer(mp);
4086 }
4087 });
4088 mediaPlayer.setOnErrorListener(new OnErrorListener() {
4089 public boolean onError(MediaPlayer mp, int what, int extra) {
4090 cleanupPlayer(mp);
4091 return true;
4092 }
4093 });
4094 mediaPlayer.start();
4095 } catch (IOException ex) {
4096 Log.w(TAG, "MediaPlayer IOException: "+ex);
4097 } catch (IllegalArgumentException ex) {
4098 Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
4099 } catch (IllegalStateException ex) {
4100 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
4102 }
4103 }
4104 }
4105
4106 private void cleanupPlayer(MediaPlayer mp) {
4107 if (mp != null) {
4108 try {
4109 mp.stop();
4110 mp.release();
4111 } catch (IllegalStateException ex) {
4112 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
4113 }
4114 }
4115 }
4116
Eric Laurentfa640152011-03-12 15:59:51 -08004117 private void setForceUse(int usage, int config) {
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004118 synchronized (mConnectedDevices) {
4119 setForceUseInt_SyncDevices(usage, config);
4120 }
Eric Laurentfa640152011-03-12 15:59:51 -08004121 }
4122
Eric Laurent05274f32012-11-29 12:48:18 -08004123 private void onPersistSafeVolumeState(int state) {
4124 Settings.Global.putInt(mContentResolver,
4125 Settings.Global.AUDIO_SAFE_VOLUME_STATE,
4126 state);
4127 }
4128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 @Override
4130 public void handleMessage(Message msg) {
Eric Laurentafbb0472011-12-15 09:04:23 -08004131 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132
Eric Laurent9bc8358d2011-11-18 16:43:31 -08004133 case MSG_SET_DEVICE_VOLUME:
4134 setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);
4135 break;
4136
4137 case MSG_SET_ALL_VOLUMES:
4138 setAllVolumes((VolumeStreamState) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 break;
4140
4141 case MSG_PERSIST_VOLUME:
Eric Laurent42b041e2013-03-29 11:36:03 -07004142 persistVolume((VolumeStreamState) msg.obj, msg.arg1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 break;
4144
Mike Lockwood5c55a052011-12-15 17:21:44 -05004145 case MSG_PERSIST_MASTER_VOLUME:
Eric Laurent83a017b2013-03-19 18:15:31 -07004146 if (mUseFixedVolume) {
4147 return;
4148 }
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004149 Settings.System.putFloatForUser(mContentResolver,
4150 Settings.System.VOLUME_MASTER,
RoboErik8a2cfc32014-05-16 11:19:38 -07004151 msg.arg1 / (float)1000.0,
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004152 UserHandle.USER_CURRENT);
Mike Lockwood5c55a052011-12-15 17:21:44 -05004153 break;
4154
Justin Koh57978ed2012-04-03 17:37:58 -07004155 case MSG_PERSIST_MASTER_VOLUME_MUTE:
Eric Laurent83a017b2013-03-19 18:15:31 -07004156 if (mUseFixedVolume) {
4157 return;
4158 }
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004159 Settings.System.putIntForUser(mContentResolver,
4160 Settings.System.VOLUME_MASTER_MUTE,
4161 msg.arg1,
Julia Reynoldsb53453f2014-08-22 11:42:43 -04004162 msg.arg2);
Justin Koh57978ed2012-04-03 17:37:58 -07004163 break;
4164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 case MSG_PERSIST_RINGER_MODE:
Glenn Kastenba195eb2011-12-13 09:30:40 -08004166 // note that the value persisted is the current ringer mode, not the
4167 // value of ringer mode as of the time the request was made to persist
John Spurlock661f2cf2014-11-17 10:29:10 -05004168 persistRingerMode(getRingerModeInternal());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 break;
4170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 case MSG_MEDIA_SERVER_DIED:
Eric Laurenteb4b8a22014-07-21 13:10:07 -07004172 if (!mSystemReady ||
4173 (AudioSystem.checkAudioFlinger() != AudioSystem.AUDIO_STATUS_OK)) {
Eric Laurent89e74ba2009-09-30 18:26:36 -07004174 Log.e(TAG, "Media server died.");
Eric Laurentafbb0472011-12-15 09:04:23 -08004175 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0,
Eric Laurent89e74ba2009-09-30 18:26:36 -07004176 null, 500);
Eric Laurentdfb881f2013-07-18 14:41:39 -07004177 break;
Eric Laurent89e74ba2009-09-30 18:26:36 -07004178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 Log.e(TAG, "Media server started.");
Eric Laurentdfb881f2013-07-18 14:41:39 -07004180
Eric Laurent3c652ca2010-06-21 20:46:26 -07004181 // indicate to audio HAL that we start the reconfiguration phase after a media
4182 // server crash
Eric Laurentdfb881f2013-07-18 14:41:39 -07004183 // Note that we only execute this when the media server
Eric Laurent3c652ca2010-06-21 20:46:26 -07004184 // process restarts after a crash, not the first time it is started.
4185 AudioSystem.setParameters("restarting=true");
4186
Glenn Kastenfd116ad2013-07-12 17:10:39 -07004187 readAndSetLowRamDevice();
4188
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004189 // Restore device connection states
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004190 synchronized (mConnectedDevices) {
4191 Set set = mConnectedDevices.entrySet();
4192 Iterator i = set.iterator();
Eric Laurent9bc8358d2011-11-18 16:43:31 -08004193 while (i.hasNext()) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004194 Map.Entry device = (Map.Entry)i.next();
4195 AudioSystem.setDeviceConnectionState(
4196 ((Integer)device.getKey()).intValue(),
4197 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004198 (String)device.getValue(),
4199 "unknown-device");
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004200 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004201 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004202 // Restore call state
4203 AudioSystem.setPhoneState(mMode);
4204
Eric Laurentd5603c12009-08-06 08:49:39 -07004205 // Restore forced usage for communcations and record
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004206 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
Eric Laurentd5603c12009-08-06 08:49:39 -07004207 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
Eric Laurentdd45d012012-10-08 09:04:34 -07004208 AudioSystem.setForceUse(AudioSystem.FOR_SYSTEM, mCameraSoundForced ?
4209 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004210
Eric Laurenta553c252009-07-17 12:17:14 -07004211 // Restore stream volumes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 int numStreamTypes = AudioSystem.getNumStreamTypes();
4213 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004215 AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
Eric Laurent9bc8358d2011-11-18 16:43:31 -08004216
4217 streamState.applyAllVolumes();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07004219
4220 // Restore ringer mode
John Spurlock661f2cf2014-11-17 10:29:10 -05004221 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent3c652ca2010-06-21 20:46:26 -07004222
Mike Lockwood90631542012-01-06 11:20:37 -05004223 // Restore master volume
4224 restoreMasterVolume();
4225
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004226 // Reset device orientation (if monitored for this device)
Eric Laurentd640bd32012-09-28 18:01:48 -07004227 if (mMonitorOrientation) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004228 setOrientationForAudioSystem();
4229 }
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07004230 if (mMonitorRotation) {
4231 setRotationForAudioSystem();
4232 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004233
Eric Laurent78472112012-05-21 08:57:21 -07004234 synchronized (mBluetoothA2dpEnabledLock) {
4235 AudioSystem.setForceUse(AudioSystem.FOR_MEDIA,
4236 mBluetoothA2dpEnabled ?
4237 AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP);
4238 }
Eric Laurentbff5ca52012-11-02 16:48:26 -07004239
4240 synchronized (mSettingsLock) {
4241 AudioSystem.setForceUse(AudioSystem.FOR_DOCK,
4242 mDockAudioMediaEnabled ?
4243 AudioSystem.FORCE_ANALOG_DOCK : AudioSystem.FORCE_NONE);
4244 }
Eric Laurent212532b2014-07-21 15:43:18 -07004245 if (mHdmiManager != null) {
4246 synchronized (mHdmiManager) {
4247 if (mHdmiTvClient != null) {
4248 setHdmiSystemAudioSupported(mHdmiSystemAudioSupported);
4249 }
4250 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09004251 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08004252
4253 synchronized (mAudioPolicies) {
4254 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
4255 policy.connectMixes();
4256 }
4257 }
4258
Eric Laurent3c652ca2010-06-21 20:46:26 -07004259 // indicate the end of reconfiguration phase to audio HAL
4260 AudioSystem.setParameters("restarting=false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 break;
4262
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004263 case MSG_UNLOAD_SOUND_EFFECTS:
4264 onUnloadSoundEffects();
4265 break;
4266
Eric Laurent117b7bb2011-01-16 17:07:27 -08004267 case MSG_LOAD_SOUND_EFFECTS:
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004268 //FIXME: onLoadSoundEffects() should be executed in a separate thread as it
4269 // can take several dozens of milliseconds to complete
4270 boolean loaded = onLoadSoundEffects();
4271 if (msg.obj != null) {
4272 LoadSoundEffectReply reply = (LoadSoundEffectReply)msg.obj;
4273 synchronized (reply) {
4274 reply.mStatus = loaded ? 0 : -1;
4275 reply.notify();
4276 }
4277 }
Eric Laurent117b7bb2011-01-16 17:07:27 -08004278 break;
4279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 case MSG_PLAY_SOUND_EFFECT:
Eric Laurent5d3eb44a2013-03-21 15:35:10 -07004281 onPlaySoundEffect(msg.arg1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 break;
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004283
4284 case MSG_BTA2DP_DOCK_TIMEOUT:
4285 // msg.obj == address of BTA2DP device
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004286 synchronized (mConnectedDevices) {
4287 makeA2dpDeviceUnavailableNow( (String) msg.obj );
4288 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004289 break;
Eric Laurentfa640152011-03-12 15:59:51 -08004290
4291 case MSG_SET_FORCE_USE:
Eric Laurentc390bed2012-07-03 12:24:05 -07004292 case MSG_SET_FORCE_BT_A2DP_USE:
Eric Laurentfa640152011-03-12 15:59:51 -08004293 setForceUse(msg.arg1, msg.arg2);
4294 break;
Jean-Michel Trivid589fea2011-04-15 11:28:10 -07004295
Eric Laurentdc03c612011-04-01 10:59:41 -07004296 case MSG_BT_HEADSET_CNCT_FAILED:
4297 resetBluetoothSco();
4298 break;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004299
4300 case MSG_SET_WIRED_DEVICE_CONNECTION_STATE:
Paul McLean10804eb2015-01-28 11:16:35 -08004301 { WiredDeviceConnectionState connectState =
4302 (WiredDeviceConnectionState)msg.obj;
4303 onSetWiredDeviceConnectionState(connectState.mType, connectState.mState,
4304 connectState.mAddress, connectState.mName);
4305 mAudioEventWakeLock.release();
4306 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004307 break;
4308
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004309 case MSG_SET_A2DP_SRC_CONNECTION_STATE:
4310 onSetA2dpSourceConnectionState((BluetoothDevice)msg.obj, msg.arg1);
4311 mAudioEventWakeLock.release();
4312 break;
4313
4314 case MSG_SET_A2DP_SINK_CONNECTION_STATE:
4315 onSetA2dpSinkConnectionState((BluetoothDevice)msg.obj, msg.arg1);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004316 mAudioEventWakeLock.release();
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004317 break;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004318
4319 case MSG_REPORT_NEW_ROUTES: {
4320 int N = mRoutesObservers.beginBroadcast();
4321 if (N > 0) {
4322 AudioRoutesInfo routes;
4323 synchronized (mCurAudioRoutes) {
4324 routes = new AudioRoutesInfo(mCurAudioRoutes);
4325 }
4326 while (N > 0) {
4327 N--;
4328 IAudioRoutesObserver obs = mRoutesObservers.getBroadcastItem(N);
4329 try {
4330 obs.dispatchAudioRoutesChanged(routes);
4331 } catch (RemoteException e) {
4332 }
4333 }
4334 }
4335 mRoutesObservers.finishBroadcast();
4336 break;
4337 }
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07004338
Eric Laurentc34dcc12012-09-10 13:51:52 -07004339 case MSG_CHECK_MUSIC_ACTIVE:
4340 onCheckMusicActive();
4341 break;
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004342
4343 case MSG_BROADCAST_AUDIO_BECOMING_NOISY:
4344 onSendBecomingNoisyIntent();
4345 break;
Eric Laurentd640bd32012-09-28 18:01:48 -07004346
4347 case MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED:
4348 case MSG_CONFIGURE_SAFE_MEDIA_VOLUME:
4349 onConfigureSafeVolume((msg.what == MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED));
4350 break;
Eric Laurent05274f32012-11-29 12:48:18 -08004351 case MSG_PERSIST_SAFE_VOLUME_STATE:
4352 onPersistSafeVolumeState(msg.arg1);
4353 break;
Jean-Michel Trivia578c482012-12-28 11:19:49 -08004354
Eric Laurent2a57ca92013-03-07 17:29:27 -08004355 case MSG_BROADCAST_BT_CONNECTION_STATE:
4356 onBroadcastScoConnectionState(msg.arg1);
4357 break;
Eric Laurent4a5eeb92014-05-06 10:49:04 -07004358
4359 case MSG_SYSTEM_READY:
4360 onSystemReady();
4361 break;
John Spurlockaa5ee4d2014-07-25 13:05:12 -04004362
4363 case MSG_PERSIST_MUSIC_ACTIVE_MS:
4364 final int musicActiveMs = msg.arg1;
4365 Settings.Secure.putIntForUser(mContentResolver,
4366 Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, musicActiveMs,
4367 UserHandle.USER_CURRENT);
4368 break;
Julia Reynoldsb53453f2014-08-22 11:42:43 -04004369 case MSG_PERSIST_MICROPHONE_MUTE:
4370 Settings.System.putIntForUser(mContentResolver,
4371 Settings.System.MICROPHONE_MUTE,
4372 msg.arg1,
4373 msg.arg2);
4374 break;
RoboErik5452e252015-02-06 15:33:53 -08004375 case MSG_UNMUTE_STREAM:
4376 onUnmuteStream(msg.arg1, msg.arg2);
4377 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 }
4379 }
4380 }
4381
Jason Parekhb1096152009-03-24 17:48:25 -07004382 private class SettingsObserver extends ContentObserver {
Eric Laurenta553c252009-07-17 12:17:14 -07004383
Jason Parekhb1096152009-03-24 17:48:25 -07004384 SettingsObserver() {
4385 super(new Handler());
4386 mContentResolver.registerContentObserver(Settings.System.getUriFor(
4387 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
Eric Laurent7ee1e4f2012-10-26 18:11:21 -07004388 mContentResolver.registerContentObserver(Settings.Global.getUriFor(
4389 Settings.Global.DOCK_AUDIO_MEDIA_ENABLED), false, this);
Jason Parekhb1096152009-03-24 17:48:25 -07004390 }
4391
4392 @Override
4393 public void onChange(boolean selfChange) {
4394 super.onChange(selfChange);
Glenn Kastenba195eb2011-12-13 09:30:40 -08004395 // FIXME This synchronized is not necessary if mSettingsLock only protects mRingerMode.
4396 // However there appear to be some missing locks around mRingerModeMutedStreams
4397 // and mRingerModeAffectedStreams, so will leave this synchronized for now.
4398 // mRingerModeMutedStreams and mMuteAffectedStreams are safe (only accessed once).
Eric Laurenta553c252009-07-17 12:17:14 -07004399 synchronized (mSettingsLock) {
Eric Laurent24e0d9b2013-10-03 18:15:07 -07004400 if (updateRingerModeAffectedStreams()) {
Eric Laurenta553c252009-07-17 12:17:14 -07004401 /*
4402 * Ensure all stream types that should be affected by ringer mode
4403 * are in the proper state.
4404 */
John Spurlock661f2cf2014-11-17 10:29:10 -05004405 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurenta553c252009-07-17 12:17:14 -07004406 }
Eric Laurent7ee1e4f2012-10-26 18:11:21 -07004407 readDockAudioSettings(mContentResolver);
Eric Laurenta553c252009-07-17 12:17:14 -07004408 }
Jason Parekhb1096152009-03-24 17:48:25 -07004409 }
Jason Parekhb1096152009-03-24 17:48:25 -07004410 }
Eric Laurenta553c252009-07-17 12:17:14 -07004411
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004412 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004413 private void makeA2dpDeviceAvailable(String address) {
Eric Laurent78472112012-05-21 08:57:21 -07004414 // enable A2DP before notifying A2DP connection to avoid unecessary processing in
4415 // audio policy manager
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004416 VolumeStreamState streamState = mStreamStates[AudioSystem.STREAM_MUSIC];
4417 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
4418 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0, streamState, 0);
Eric Laurent78472112012-05-21 08:57:21 -07004419 setBluetoothA2dpOnInt(true);
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004420 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
4421 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004422 address,
4423 "a2dp-device");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004424 // Reset A2DP suspend state each time a new sink is connected
4425 AudioSystem.setParameters("A2dpSuspended=false");
4426 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
4427 address);
4428 }
4429
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004430 private void onSendBecomingNoisyIntent() {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004431 sendBroadcastToAll(new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
Mike Lockwood98418182012-05-10 17:13:20 -07004432 }
4433
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004434 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004435 private void makeA2dpDeviceUnavailableNow(String address) {
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004436 synchronized (mA2dpAvrcpLock) {
4437 mAvrcpAbsVolSupported = false;
4438 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004439 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
4440 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004441 address,
4442 "a2dp-device");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004443 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
RoboErik5535ea82014-09-25 14:53:16 -07004444 synchronized (mCurAudioRoutes) {
4445 // Remove A2DP routes as well
John Spurlock61560172015-02-06 19:46:04 -05004446 if (mCurAudioRoutes.bluetoothName != null) {
4447 mCurAudioRoutes.bluetoothName = null;
RoboErik5535ea82014-09-25 14:53:16 -07004448 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4449 SENDMSG_NOOP, 0, 0, null, 0);
4450 }
4451 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004452 }
4453
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004454 // must be called synchronized on mConnectedDevices
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004455 private void makeA2dpDeviceUnavailableLater(String address) {
Eric Laurent3b591262010-04-20 07:01:00 -07004456 // prevent any activity on the A2DP audio output to avoid unwanted
4457 // reconnection of the sink.
4458 AudioSystem.setParameters("A2dpSuspended=true");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004459 // the device will be made unavailable later, so consider it disconnected right away
4460 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
4461 // send the delayed message to make the device unavailable later
4462 Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
4463 mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
4464
4465 }
4466
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004467 // must be called synchronized on mConnectedDevices
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004468 private void makeA2dpSrcAvailable(String address) {
4469 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
4470 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004471 address,
4472 "a2dp-device");
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004473 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP),
4474 address);
4475 }
4476
4477 // must be called synchronized on mConnectedDevices
4478 private void makeA2dpSrcUnavailable(String address) {
4479 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP,
4480 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004481 address,
4482 "a2dp-device");
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004483 mConnectedDevices.remove(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP);
4484 }
4485
4486 // must be called synchronized on mConnectedDevices
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004487 private void cancelA2dpDeviceTimeout() {
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07004488 mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
4489 }
4490
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004491 // must be called synchronized on mConnectedDevices
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004492 private boolean hasScheduledA2dpDockTimeout() {
4493 return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
4494 }
4495
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004496 private void onSetA2dpSinkConnectionState(BluetoothDevice btDevice, int state)
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004497 {
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004498 if (DEBUG_VOL) {
4499 Log.d(TAG, "onSetA2dpSinkConnectionState btDevice="+btDevice+"state="+state);
4500 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004501 if (btDevice == null) {
4502 return;
4503 }
4504 String address = btDevice.getAddress();
4505 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4506 address = "";
4507 }
John Du5a0cf7a2013-07-19 11:30:34 -07004508
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004509 synchronized (mConnectedDevices) {
4510 boolean isConnected =
4511 (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
4512 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
4513
4514 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
4515 if (btDevice.isBluetoothDock()) {
4516 if (state == BluetoothProfile.STATE_DISCONNECTED) {
4517 // introduction of a delay for transient disconnections of docks when
4518 // power is rapidly turned off/on, this message will be canceled if
4519 // we reconnect the dock under a preset delay
4520 makeA2dpDeviceUnavailableLater(address);
4521 // the next time isConnected is evaluated, it will be false for the dock
4522 }
4523 } else {
4524 makeA2dpDeviceUnavailableNow(address);
4525 }
Dianne Hackborn632ca412012-06-14 19:34:10 -07004526 synchronized (mCurAudioRoutes) {
John Spurlock61560172015-02-06 19:46:04 -05004527 if (mCurAudioRoutes.bluetoothName != null) {
4528 mCurAudioRoutes.bluetoothName = null;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004529 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4530 SENDMSG_NOOP, 0, 0, null, 0);
4531 }
4532 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004533 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
4534 if (btDevice.isBluetoothDock()) {
4535 // this could be a reconnection after a transient disconnection
4536 cancelA2dpDeviceTimeout();
4537 mDockAddress = address;
4538 } else {
4539 // this could be a connection of another A2DP device before the timeout of
4540 // a dock: cancel the dock timeout, and make the dock unavailable now
4541 if(hasScheduledA2dpDockTimeout()) {
4542 cancelA2dpDeviceTimeout();
4543 makeA2dpDeviceUnavailableNow(mDockAddress);
4544 }
4545 }
4546 makeA2dpDeviceAvailable(address);
Dianne Hackborn632ca412012-06-14 19:34:10 -07004547 synchronized (mCurAudioRoutes) {
4548 String name = btDevice.getAliasName();
John Spurlock61560172015-02-06 19:46:04 -05004549 if (!TextUtils.equals(mCurAudioRoutes.bluetoothName, name)) {
4550 mCurAudioRoutes.bluetoothName = name;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004551 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4552 SENDMSG_NOOP, 0, 0, null, 0);
4553 }
4554 }
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004555 }
4556 }
4557 }
4558
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004559 private void onSetA2dpSourceConnectionState(BluetoothDevice btDevice, int state)
4560 {
4561 if (DEBUG_VOL) {
4562 Log.d(TAG, "onSetA2dpSourceConnectionState btDevice="+btDevice+" state="+state);
4563 }
4564 if (btDevice == null) {
4565 return;
4566 }
4567 String address = btDevice.getAddress();
4568 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4569 address = "";
4570 }
4571
4572 synchronized (mConnectedDevices) {
4573 boolean isConnected =
4574 (mConnectedDevices.containsKey(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP) &&
4575 mConnectedDevices.get(AudioSystem.DEVICE_IN_BLUETOOTH_A2DP).equals(address));
4576
4577 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
4578 makeA2dpSrcUnavailable(address);
4579 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
4580 makeA2dpSrcAvailable(address);
4581 }
4582 }
4583 }
4584
John Du5a0cf7a2013-07-19 11:30:34 -07004585 public void avrcpSupportsAbsoluteVolume(String address, boolean support) {
4586 // address is not used for now, but may be used when multiple a2dp devices are supported
4587 synchronized (mA2dpAvrcpLock) {
4588 mAvrcpAbsVolSupported = support;
Matthew Xiec9d1d5f2013-09-12 00:32:22 -07004589 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
Eric Laurentcd772d02013-10-30 18:31:07 -07004590 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0,
4591 mStreamStates[AudioSystem.STREAM_MUSIC], 0);
4592 sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
4593 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 0,
4594 mStreamStates[AudioSystem.STREAM_RING], 0);
John Du5a0cf7a2013-07-19 11:30:34 -07004595 }
4596 }
4597
Paul McLean10804eb2015-01-28 11:16:35 -08004598 private boolean handleDeviceConnection(boolean connect, int device, String address, String deviceName) {
4599 Slog.i(TAG, "handleDeviceConnection(" + connect +
4600 " dev:" + Integer.toHexString(device) +
RoboErik5452e252015-02-06 15:33:53 -08004601 " address:" + address +
Paul McLean10804eb2015-01-28 11:16:35 -08004602 " name:" + deviceName + ")");
Eric Laurent59f48272012-04-05 19:42:21 -07004603 synchronized (mConnectedDevices) {
4604 boolean isConnected = (mConnectedDevices.containsKey(device) &&
Paul McLean10804eb2015-01-28 11:16:35 -08004605 (address.isEmpty() || mConnectedDevices.get(device).equals(address)));
Eric Laurent59f48272012-04-05 19:42:21 -07004606
Paul McLean10804eb2015-01-28 11:16:35 -08004607 if (isConnected && !connect) {
Eric Laurent59f48272012-04-05 19:42:21 -07004608 AudioSystem.setDeviceConnectionState(device,
4609 AudioSystem.DEVICE_STATE_UNAVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004610 address, deviceName);
Eric Laurent59f48272012-04-05 19:42:21 -07004611 mConnectedDevices.remove(device);
4612 return true;
Paul McLean10804eb2015-01-28 11:16:35 -08004613 } else if (!isConnected && connect) {
Eric Laurent59f48272012-04-05 19:42:21 -07004614 AudioSystem.setDeviceConnectionState(device,
4615 AudioSystem.DEVICE_STATE_AVAILABLE,
Paul McLean10804eb2015-01-28 11:16:35 -08004616 address, deviceName);
4617 mConnectedDevices.put(new Integer(device), address);
Eric Laurent59f48272012-04-05 19:42:21 -07004618 return true;
4619 }
4620 }
4621 return false;
4622 }
4623
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004624 // Devices which removal triggers intent ACTION_AUDIO_BECOMING_NOISY. The intent is only
4625 // sent if none of these devices is connected.
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004626 // Access synchronized on mConnectedDevices
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004627 int mBecomingNoisyIntentDevices =
4628 AudioSystem.DEVICE_OUT_WIRED_HEADSET | AudioSystem.DEVICE_OUT_WIRED_HEADPHONE |
Eric Laurent948d3272014-05-16 15:18:45 -07004629 AudioSystem.DEVICE_OUT_ALL_A2DP | AudioSystem.DEVICE_OUT_HDMI |
Eric Laurent794da7a2012-08-30 11:30:16 -07004630 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET | AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET |
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004631 AudioSystem.DEVICE_OUT_ALL_USB | AudioSystem.DEVICE_OUT_LINE;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004632
4633 // must be called before removing the device from mConnectedDevices
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08004634 // Called synchronized on mConnectedDevices
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004635 private int checkSendBecomingNoisyIntent(int device, int state) {
4636 int delay = 0;
4637 if ((state == 0) && ((device & mBecomingNoisyIntentDevices) != 0)) {
4638 int devices = 0;
4639 for (int dev : mConnectedDevices.keySet()) {
Eric Laurent27c30e42014-08-27 12:36:33 -07004640 if (((dev & AudioSystem.DEVICE_BIT_IN) == 0) &&
4641 ((dev & mBecomingNoisyIntentDevices) != 0)) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004642 devices |= dev;
4643 }
4644 }
4645 if (devices == device) {
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004646 sendMsg(mAudioHandler,
4647 MSG_BROADCAST_AUDIO_BECOMING_NOISY,
4648 SENDMSG_REPLACE,
4649 0,
4650 0,
4651 null,
4652 0);
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004653 delay = 1000;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004654 }
4655 }
4656
Mike Lockwood0a40ec22014-05-21 10:08:50 -07004657 if (mAudioHandler.hasMessages(MSG_SET_A2DP_SRC_CONNECTION_STATE) ||
4658 mAudioHandler.hasMessages(MSG_SET_A2DP_SINK_CONNECTION_STATE) ||
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004659 mAudioHandler.hasMessages(MSG_SET_WIRED_DEVICE_CONNECTION_STATE)) {
Eric Laurentadbe8bf2014-11-03 18:26:32 -08004660 synchronized (mLastDeviceConnectMsgTime) {
4661 long time = SystemClock.uptimeMillis();
4662 if (mLastDeviceConnectMsgTime > time) {
Matthew Xiec525cf72015-01-22 20:13:17 -08004663 delay = (int)(mLastDeviceConnectMsgTime - time) + 30;
Eric Laurentadbe8bf2014-11-03 18:26:32 -08004664 }
4665 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004666 }
4667 return delay;
4668 }
4669
Paul McLean10804eb2015-01-28 11:16:35 -08004670 private void sendDeviceConnectionIntent(int device, int state, String address, String deviceName)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004671 {
Paul McLean10804eb2015-01-28 11:16:35 -08004672 Slog.i(TAG, "sendDeviceConnectionIntent(dev:0x" + Integer.toHexString(device) +
4673 " state:0x" + Integer.toHexString(state) +
4674 " address:" + address +
4675 " name:" + deviceName + ");");
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004676 Intent intent = new Intent();
4677
Paul McLean10804eb2015-01-28 11:16:35 -08004678 intent.putExtra(CONNECT_INTENT_KEY_STATE, state);
4679 intent.putExtra(CONNECT_INTENT_KEY_ADDRESS, address);
4680 intent.putExtra(CONNECT_INTENT_KEY_PORT_NAME, deviceName);
4681
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004682 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4683
Dianne Hackborn632ca412012-06-14 19:34:10 -07004684 int connType = 0;
4685
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004686 if (device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) {
Dianne Hackborn632ca412012-06-14 19:34:10 -07004687 connType = AudioRoutesInfo.MAIN_HEADSET;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004688 intent.setAction(Intent.ACTION_HEADSET_PLUG);
4689 intent.putExtra("microphone", 1);
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004690 } else if (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE ||
4691 device == AudioSystem.DEVICE_OUT_LINE) {
4692 /*do apps care about line-out vs headphones?*/
Dianne Hackborn632ca412012-06-14 19:34:10 -07004693 connType = AudioRoutesInfo.MAIN_HEADPHONES;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004694 intent.setAction(Intent.ACTION_HEADSET_PLUG);
4695 intent.putExtra("microphone", 0);
Eric Laurent6fa42452015-01-09 15:09:40 -08004696 } else if (device == AudioSystem.DEVICE_OUT_HDMI ||
4697 device == AudioSystem.DEVICE_OUT_HDMI_ARC) {
Dianne Hackborn632ca412012-06-14 19:34:10 -07004698 connType = AudioRoutesInfo.MAIN_HDMI;
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004699 configureHdmiPlugIntent(intent, state);
Paul McLean10804eb2015-01-28 11:16:35 -08004700 } else if (device == AudioSystem.DEVICE_OUT_USB_DEVICE) {
4701 connType = AudioRoutesInfo.MAIN_USB;
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004702 }
4703
Dianne Hackborn632ca412012-06-14 19:34:10 -07004704 synchronized (mCurAudioRoutes) {
4705 if (connType != 0) {
John Spurlock61560172015-02-06 19:46:04 -05004706 int newConn = mCurAudioRoutes.mainType;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004707 if (state != 0) {
4708 newConn |= connType;
4709 } else {
4710 newConn &= ~connType;
4711 }
John Spurlock61560172015-02-06 19:46:04 -05004712 if (newConn != mCurAudioRoutes.mainType) {
4713 mCurAudioRoutes.mainType = newConn;
Dianne Hackborn632ca412012-06-14 19:34:10 -07004714 sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
4715 SENDMSG_NOOP, 0, 0, null, 0);
4716 }
4717 }
4718 }
4719
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004720 final long ident = Binder.clearCallingIdentity();
4721 try {
4722 ActivityManagerNative.broadcastStickyIntent(intent, null, UserHandle.USER_ALL);
4723 } finally {
4724 Binder.restoreCallingIdentity(ident);
4725 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004726 }
4727
Paul McLean10804eb2015-01-28 11:16:35 -08004728 private void onSetWiredDeviceConnectionState(int device, int state, String address,
4729 String deviceName)
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004730 {
Paul McLean10804eb2015-01-28 11:16:35 -08004731 Slog.i(TAG, "onSetWiredDeviceConnectionState(dev:" + Integer.toHexString(device)
4732 + " state:" + Integer.toHexString(state)
4733 + " address:" + address
4734 + " deviceName:" + deviceName + ");");
4735
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004736 synchronized (mConnectedDevices) {
4737 if ((state == 0) && ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004738 (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) ||
4739 (device == AudioSystem.DEVICE_OUT_LINE))) {
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004740 setBluetoothA2dpOnInt(true);
4741 }
Eric Laurentae4506e2014-05-29 16:04:32 -07004742 boolean isUsb = ((device & ~AudioSystem.DEVICE_OUT_ALL_USB) == 0) ||
4743 (((device & AudioSystem.DEVICE_BIT_IN) != 0) &&
4744 ((device & ~AudioSystem.DEVICE_IN_ALL_USB) == 0));
Paul McLean10804eb2015-01-28 11:16:35 -08004745 handleDeviceConnection(state == 1, device, address, deviceName);
Eric Laurentf1a457d2012-09-20 16:27:23 -07004746 if (state != 0) {
4747 if ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
Jon Eklund43cc8bb2014-07-28 16:07:24 -05004748 (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) ||
4749 (device == AudioSystem.DEVICE_OUT_LINE)) {
Eric Laurentf1a457d2012-09-20 16:27:23 -07004750 setBluetoothA2dpOnInt(false);
4751 }
4752 if ((device & mSafeMediaVolumeDevices) != 0) {
4753 sendMsg(mAudioHandler,
4754 MSG_CHECK_MUSIC_ACTIVE,
4755 SENDMSG_REPLACE,
4756 0,
4757 0,
4758 null,
4759 MUSIC_ACTIVE_POLL_PERIOD_MS);
4760 }
Eric Laurent212532b2014-07-21 15:43:18 -07004761 // Television devices without CEC service apply software volume on HDMI output
4762 if (isPlatformTelevision() && ((device & AudioSystem.DEVICE_OUT_HDMI) != 0)) {
4763 mFixedVolumeDevices |= AudioSystem.DEVICE_OUT_HDMI;
4764 checkAllFixedVolumeDevices();
4765 if (mHdmiManager != null) {
4766 synchronized (mHdmiManager) {
4767 if (mHdmiPlaybackClient != null) {
4768 mHdmiCecSink = false;
4769 mHdmiPlaybackClient.queryDisplayStatus(mHdmiDisplayStatusCallback);
4770 }
4771 }
4772 }
4773 }
4774 } else {
4775 if (isPlatformTelevision() && ((device & AudioSystem.DEVICE_OUT_HDMI) != 0)) {
4776 if (mHdmiManager != null) {
4777 synchronized (mHdmiManager) {
4778 mHdmiCecSink = false;
4779 }
4780 }
4781 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004782 }
Paul McLean10804eb2015-01-28 11:16:35 -08004783 if (!isUsb && device != AudioSystem.DEVICE_IN_WIRED_HEADSET) {
4784 sendDeviceConnectionIntent(device, state, address, deviceName);
Mike Lockwooddb454842012-09-18 11:16:57 -07004785 }
Eric Laurentb1fbaac2012-05-29 09:24:28 -07004786 }
4787 }
4788
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004789 private void configureHdmiPlugIntent(Intent intent, int state) {
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004790 intent.setAction(AudioManager.ACTION_HDMI_AUDIO_PLUG);
4791 intent.putExtra(AudioManager.EXTRA_AUDIO_PLUG_STATE, state);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004792 if (state == 1) {
4793 ArrayList<AudioPort> ports = new ArrayList<AudioPort>();
4794 int[] portGeneration = new int[1];
4795 int status = AudioSystem.listAudioPorts(ports, portGeneration);
4796 if (status == AudioManager.SUCCESS) {
4797 for (AudioPort port : ports) {
4798 if (port instanceof AudioDevicePort) {
4799 final AudioDevicePort devicePort = (AudioDevicePort) port;
Eric Laurent6fa42452015-01-09 15:09:40 -08004800 if (devicePort.type() == AudioManager.DEVICE_OUT_HDMI ||
4801 devicePort.type() == AudioManager.DEVICE_OUT_HDMI_ARC) {
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004802 // format the list of supported encodings
4803 int[] formats = devicePort.formats();
4804 if (formats.length > 0) {
4805 ArrayList<Integer> encodingList = new ArrayList(1);
4806 for (int format : formats) {
4807 // a format in the list can be 0, skip it
4808 if (format != AudioFormat.ENCODING_INVALID) {
4809 encodingList.add(format);
4810 }
4811 }
4812 int[] encodingArray = new int[encodingList.size()];
4813 for (int i = 0 ; i < encodingArray.length ; i++) {
4814 encodingArray[i] = encodingList.get(i);
4815 }
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004816 intent.putExtra(AudioManager.EXTRA_ENCODINGS, encodingArray);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004817 }
4818 // find the maximum supported number of channels
4819 int maxChannels = 0;
4820 for (int mask : devicePort.channelMasks()) {
4821 int channelCount = AudioFormat.channelCountFromOutChannelMask(mask);
4822 if (channelCount > maxChannels) {
4823 maxChannels = channelCount;
4824 }
4825 }
Jean-Michel Trivic5258432014-08-27 15:46:54 -07004826 intent.putExtra(AudioManager.EXTRA_MAX_CHANNEL_COUNT, maxChannels);
Jean-Michel Trivi37d78042014-08-10 14:59:15 -07004827 }
4828 }
4829 }
4830 }
4831 }
4832 }
4833
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07004834 /* cache of the address of the last dock the device was connected to */
4835 private String mDockAddress;
4836
Eric Laurenta553c252009-07-17 12:17:14 -07004837 /**
4838 * Receiver for misc intent broadcasts the Phone app cares about.
4839 */
4840 private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
4841 @Override
4842 public void onReceive(Context context, Intent intent) {
4843 String action = intent.getAction();
Eric Laurentae4506e2014-05-29 16:04:32 -07004844 int outDevice;
4845 int inDevice;
Eric Laurent59f48272012-04-05 19:42:21 -07004846 int state;
Eric Laurenta553c252009-07-17 12:17:14 -07004847
Jean-Michel Trivi758559e2010-03-09 09:26:08 -08004848 if (action.equals(Intent.ACTION_DOCK_EVENT)) {
4849 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4850 Intent.EXTRA_DOCK_STATE_UNDOCKED);
4851 int config;
4852 switch (dockState) {
4853 case Intent.EXTRA_DOCK_STATE_DESK:
4854 config = AudioSystem.FORCE_BT_DESK_DOCK;
4855 break;
4856 case Intent.EXTRA_DOCK_STATE_CAR:
4857 config = AudioSystem.FORCE_BT_CAR_DOCK;
4858 break;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05004859 case Intent.EXTRA_DOCK_STATE_LE_DESK:
Eric Laurent08ed1b92012-11-05 14:54:12 -08004860 config = AudioSystem.FORCE_ANALOG_DOCK;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05004861 break;
4862 case Intent.EXTRA_DOCK_STATE_HE_DESK:
4863 config = AudioSystem.FORCE_DIGITAL_DOCK;
4864 break;
Jean-Michel Trivi758559e2010-03-09 09:26:08 -08004865 case Intent.EXTRA_DOCK_STATE_UNDOCKED:
4866 default:
4867 config = AudioSystem.FORCE_NONE;
4868 }
Eric Laurent08ed1b92012-11-05 14:54:12 -08004869 // Low end docks have a menu to enable or disable audio
4870 // (see mDockAudioMediaEnabled)
4871 if (!((dockState == Intent.EXTRA_DOCK_STATE_LE_DESK) ||
4872 ((dockState == Intent.EXTRA_DOCK_STATE_UNDOCKED) &&
4873 (mDockState == Intent.EXTRA_DOCK_STATE_LE_DESK)))) {
4874 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
4875 }
4876 mDockState = dockState;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07004877 } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
Eric Laurent59f48272012-04-05 19:42:21 -07004878 state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07004879 BluetoothProfile.STATE_DISCONNECTED);
Eric Laurentae4506e2014-05-29 16:04:32 -07004880 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
4881 inDevice = AudioSystem.DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Nick Pellya56d1c72009-08-19 14:49:29 -07004882 String address = null;
Eric Laurentdca56b92011-09-02 14:20:56 -07004883
4884 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
4885 if (btDevice == null) {
4886 return;
4887 }
4888
4889 address = btDevice.getAddress();
4890 BluetoothClass btClass = btDevice.getBluetoothClass();
4891 if (btClass != null) {
4892 switch (btClass.getDeviceClass()) {
4893 case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
4894 case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
Eric Laurentae4506e2014-05-29 16:04:32 -07004895 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurentdca56b92011-09-02 14:20:56 -07004896 break;
4897 case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
Eric Laurentae4506e2014-05-29 16:04:32 -07004898 outDevice = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurentdca56b92011-09-02 14:20:56 -07004899 break;
Eric Laurentd5603c12009-08-06 08:49:39 -07004900 }
4901 }
4902
Eric Laurentdca56b92011-09-02 14:20:56 -07004903 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
4904 address = "";
4905 }
Eric Laurentd5603c12009-08-06 08:49:39 -07004906
Eric Laurent59f48272012-04-05 19:42:21 -07004907 boolean connected = (state == BluetoothProfile.STATE_CONNECTED);
Paul McLean10804eb2015-01-28 11:16:35 -08004908 boolean success =
4909 handleDeviceConnection(connected, outDevice, address, "Bluetooth Headset") &&
4910 handleDeviceConnection(connected, inDevice, address, "Bluetooth Headset");
Eric Laurentae4506e2014-05-29 16:04:32 -07004911 if (success) {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004912 synchronized (mScoClients) {
Eric Laurent59f48272012-04-05 19:42:21 -07004913 if (connected) {
4914 mBluetoothHeadsetDevice = btDevice;
4915 } else {
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004916 mBluetoothHeadsetDevice = null;
4917 resetBluetoothSco();
Eric Laurent6bc7f2c2011-11-29 18:49:40 -08004918 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004919 }
Eric Laurenta553c252009-07-17 12:17:14 -07004920 }
Paul McLeandf361462014-04-10 16:02:55 -07004921 } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004922 boolean broadcast = false;
Eric Laurent59f48272012-04-05 19:42:21 -07004923 int scoAudioState = AudioManager.SCO_AUDIO_STATE_ERROR;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004924 synchronized (mScoClients) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004925 int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
Eric Laurentdc03c612011-04-01 10:59:41 -07004926 // broadcast intent if the connection was initated by AudioService
4927 if (!mScoClients.isEmpty() &&
4928 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
4929 mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
4930 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004931 broadcast = true;
4932 }
4933 switch (btState) {
4934 case BluetoothHeadset.STATE_AUDIO_CONNECTED:
Eric Laurent59f48272012-04-05 19:42:21 -07004935 scoAudioState = AudioManager.SCO_AUDIO_STATE_CONNECTED;
Eric Laurentdc03c612011-04-01 10:59:41 -07004936 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
4937 mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
4938 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004939 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004940 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004941 break;
4942 case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
Eric Laurent59f48272012-04-05 19:42:21 -07004943 scoAudioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
Eric Laurent62ef7672010-11-24 10:58:32 -08004944 mScoAudioState = SCO_STATE_INACTIVE;
Eric Laurentd7454be2011-09-14 08:45:58 -07004945 clearAllScoClients(0, false);
Eric Laurent62ef7672010-11-24 10:58:32 -08004946 break;
4947 case BluetoothHeadset.STATE_AUDIO_CONNECTING:
Eric Laurentdc03c612011-04-01 10:59:41 -07004948 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
4949 mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
4950 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
Eric Laurent62ef7672010-11-24 10:58:32 -08004951 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004952 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004953 default:
4954 // do not broadcast CONNECTING or invalid state
4955 broadcast = false;
4956 break;
Eric Laurent3def1ee2010-03-17 23:26:26 -07004957 }
4958 }
Eric Laurent62ef7672010-11-24 10:58:32 -08004959 if (broadcast) {
Eric Laurent59f48272012-04-05 19:42:21 -07004960 broadcastScoConnectionState(scoAudioState);
Eric Laurentdc03c612011-04-01 10:59:41 -07004961 //FIXME: this is to maintain compatibility with deprecated intent
4962 // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Eric Laurent62ef7672010-11-24 10:58:32 -08004963 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
Eric Laurent59f48272012-04-05 19:42:21 -07004964 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, scoAudioState);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004965 sendStickyBroadcastToAll(newIntent);
Eric Laurent62ef7672010-11-24 10:58:32 -08004966 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004967 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
Jon Eklund318f0fe2014-01-23 17:53:48 -06004968 if (mMonitorRotation) {
4969 mOrientationListener.onOrientationChanged(0); //argument is ignored anyway
4970 mOrientationListener.enable();
4971 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004972 AudioSystem.setParameters("screen_state=on");
4973 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Jon Eklund318f0fe2014-01-23 17:53:48 -06004974 if (mMonitorRotation) {
4975 //reduce wakeups (save current) by only listening when display is on
4976 mOrientationListener.disable();
4977 }
Eric Laurent950e8cb2011-10-13 08:57:54 -07004978 AudioSystem.setParameters("screen_state=off");
Dianne Hackborn961cae92013-03-20 14:59:43 -07004979 } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07004980 handleConfigurationChanged(context);
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004981 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004982 // attempt to stop music playback for background user
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004983 sendMsg(mAudioHandler,
4984 MSG_BROADCAST_AUDIO_BECOMING_NOISY,
4985 SENDMSG_REPLACE,
4986 0,
4987 0,
4988 null,
4989 0);
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004990 // the current audio focus owner is no longer valid
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07004991 mMediaFocusControl.discardAudioFocusOwner();
Jean-Michel Trivif4a8eb22012-10-29 12:42:55 -07004992
Eric Laurent5bfaeae2012-09-21 18:44:48 -07004993 // load volume settings for new user
Eric Laurentbc0fab1f2012-09-19 11:24:41 -07004994 readAudioSettings(true /*userSwitch*/);
4995 // preserve STREAM_MUSIC volume from one user to the next.
4996 sendMsg(mAudioHandler,
4997 MSG_SET_ALL_VOLUMES,
4998 SENDMSG_QUEUE,
4999 0,
5000 0,
5001 mStreamStates[AudioSystem.STREAM_MUSIC], 0);
Eric Laurenta553c252009-07-17 12:17:14 -07005002 }
5003 }
Paul McLeanc837a452014-04-09 09:04:43 -07005004 } // end class AudioServiceBroadcastReceiver
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005005
5006 //==========================================================================================
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005007 // RemoteControlDisplay / RemoteControlClient / Remote info
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005008 //==========================================================================================
Jean-Michel Trivif108cdd92013-09-27 18:37:36 -07005009 public boolean registerRemoteController(IRemoteControlDisplay rcd, int w, int h,
5010 ComponentName listenerComp) {
5011 return mMediaFocusControl.registerRemoteController(rcd, w, h, listenerComp);
5012 }
5013
Jean-Michel Trivi7ddd2262013-09-01 18:06:45 -07005014 public boolean registerRemoteControlDisplay(IRemoteControlDisplay rcd, int w, int h) {
Jean-Michel Trivif108cdd92013-09-27 18:37:36 -07005015 return mMediaFocusControl.registerRemoteControlDisplay(rcd, w, h);
Jean-Michel Trivi8f619182011-07-21 15:10:10 -07005016 }
Jean-Michel Trivid327f212010-03-16 21:44:33 -07005017
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07005018 public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005019 mMediaFocusControl.unregisterRemoteControlDisplay(rcd);
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07005020 }
5021
5022 public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005023 mMediaFocusControl.remoteControlDisplayUsesBitmapSize(rcd, w, h);
Jean-Michel Trivi4426e422011-08-18 19:16:47 -07005024 }
5025
Jean-Michel Trivic3c4bab2013-04-19 08:56:50 -07005026 public void remoteControlDisplayWantsPlaybackPositionSync(IRemoteControlDisplay rcd,
5027 boolean wantsSync) {
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005028 mMediaFocusControl.remoteControlDisplayWantsPlaybackPositionSync(rcd, wantsSync);
5029 }
5030
John Spurlock3346a802014-05-20 16:25:37 -04005031 @Override
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005032 public void setRemoteStreamVolume(int index) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005033 enforceVolumeController("set the remote stream volume");
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005034 mMediaFocusControl.setRemoteStreamVolume(index);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07005035 }
5036
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005037 //==========================================================================================
5038 // Audio Focus
5039 //==========================================================================================
Jean-Michel Trivifd6ad742014-11-10 14:38:30 -08005040 public int requestAudioFocus(AudioAttributes aa, int durationHint, IBinder cb,
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005041 IAudioFocusDispatcher fd, String clientId, String callingPackageName, int flags,
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005042 IAudioPolicyCallback pcb) {
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005043 // permission checks
5044 if ((flags & AudioManager.AUDIOFOCUS_FLAG_LOCK) == AudioManager.AUDIOFOCUS_FLAG_LOCK) {
John Spurlock61560172015-02-06 19:46:04 -05005045 if (AudioSystem.IN_VOICE_COMM_FOCUS_ID.equals(clientId)) {
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005046 if (PackageManager.PERMISSION_GRANTED != mContext.checkCallingOrSelfPermission(
5047 android.Manifest.permission.MODIFY_PHONE_STATE)) {
5048 Log.e(TAG, "Invalid permission to (un)lock audio focus", new Exception());
5049 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
5050 }
5051 } else {
5052 // only a registered audio policy can be used to lock focus
5053 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005054 if (!mAudioPolicies.containsKey(pcb.asBinder())) {
5055 Log.e(TAG, "Invalid unregistered AudioPolicy to (un)lock audio focus");
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005056 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
5057 }
5058 }
5059 }
5060 }
5061
Jean-Michel Trivifd6ad742014-11-10 14:38:30 -08005062 return mMediaFocusControl.requestAudioFocus(aa, durationHint, cb, fd,
5063 clientId, callingPackageName, flags);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005064 }
5065
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005066 public int abandonAudioFocus(IAudioFocusDispatcher fd, String clientId, AudioAttributes aa) {
5067 return mMediaFocusControl.abandonAudioFocus(fd, clientId, aa);
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005068 }
5069
5070 public void unregisterAudioFocusClient(String clientId) {
5071 mMediaFocusControl.unregisterAudioFocusClient(clientId);
Jean-Michel Trivi3114ce32012-06-11 15:03:52 -07005072 }
5073
Jean-Michel Trivi23805662013-07-31 14:19:18 -07005074 public int getCurrentAudioFocus() {
5075 return mMediaFocusControl.getCurrentAudioFocus();
5076 }
5077
John Spurlock5e783732015-02-19 10:28:59 -05005078 private boolean readCameraSoundForced() {
5079 return SystemProperties.getBoolean("audio.camerasound.force", false) ||
5080 mContext.getResources().getBoolean(
5081 com.android.internal.R.bool.config_camera_sound_forced);
5082 }
5083
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005084 //==========================================================================================
5085 // Device orientation
5086 //==========================================================================================
5087 /**
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005088 * Handles device configuration changes that may map to a change in the orientation
5089 * or orientation.
5090 * Monitoring orientation and rotation is optional, and is defined by the definition and value
5091 * of the "ro.audio.monitorOrientation" and "ro.audio.monitorRotation" system properties.
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005092 */
5093 private void handleConfigurationChanged(Context context) {
5094 try {
5095 // reading new orientation "safely" (i.e. under try catch) in case anything
5096 // goes wrong when obtaining resources and configuration
Eric Laurentd640bd32012-09-28 18:01:48 -07005097 Configuration config = context.getResources().getConfiguration();
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005098 // TODO merge rotation and orientation
Eric Laurentd640bd32012-09-28 18:01:48 -07005099 if (mMonitorOrientation) {
5100 int newOrientation = config.orientation;
5101 if (newOrientation != mDeviceOrientation) {
5102 mDeviceOrientation = newOrientation;
5103 setOrientationForAudioSystem();
5104 }
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005105 }
Eric Laurentd640bd32012-09-28 18:01:48 -07005106 sendMsg(mAudioHandler,
5107 MSG_CONFIGURE_SAFE_MEDIA_VOLUME,
5108 SENDMSG_REPLACE,
5109 0,
5110 0,
5111 null,
5112 0);
Eric Laurentdd45d012012-10-08 09:04:34 -07005113
John Spurlock5e783732015-02-19 10:28:59 -05005114 boolean cameraSoundForced = readCameraSoundForced();
Eric Laurentdd45d012012-10-08 09:04:34 -07005115 synchronized (mSettingsLock) {
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005116 boolean cameraSoundForcedChanged = false;
Eric Laurentdd45d012012-10-08 09:04:34 -07005117 synchronized (mCameraSoundForced) {
5118 if (cameraSoundForced != mCameraSoundForced) {
5119 mCameraSoundForced = cameraSoundForced;
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005120 cameraSoundForcedChanged = true;
Eric Laurentdd45d012012-10-08 09:04:34 -07005121 }
5122 }
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005123 if (cameraSoundForcedChanged) {
5124 if (!isPlatformTelevision()) {
5125 VolumeStreamState s = mStreamStates[AudioSystem.STREAM_SYSTEM_ENFORCED];
5126 if (cameraSoundForced) {
5127 s.setAllIndexesToMax();
5128 mRingerModeAffectedStreams &=
5129 ~(1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
5130 } else {
5131 s.setAllIndexes(mStreamStates[AudioSystem.STREAM_SYSTEM]);
5132 mRingerModeAffectedStreams |=
5133 (1 << AudioSystem.STREAM_SYSTEM_ENFORCED);
5134 }
5135 // take new state into account for streams muted by ringer mode
John Spurlock661f2cf2014-11-17 10:29:10 -05005136 setRingerModeInt(getRingerModeInternal(), false);
Eric Laurent8fa4d6f2014-10-30 14:13:03 -07005137 }
5138
5139 sendMsg(mAudioHandler,
5140 MSG_SET_FORCE_USE,
5141 SENDMSG_QUEUE,
5142 AudioSystem.FOR_SYSTEM,
5143 cameraSoundForced ?
5144 AudioSystem.FORCE_SYSTEM_ENFORCED : AudioSystem.FORCE_NONE,
5145 null,
5146 0);
5147
5148 sendMsg(mAudioHandler,
5149 MSG_SET_ALL_VOLUMES,
5150 SENDMSG_QUEUE,
5151 0,
5152 0,
5153 mStreamStates[AudioSystem.STREAM_SYSTEM_ENFORCED], 0);
5154 }
Eric Laurentdd45d012012-10-08 09:04:34 -07005155 }
John Spurlock3346a802014-05-20 16:25:37 -04005156 mVolumeController.setLayoutDirection(config.getLayoutDirection());
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005157 } catch (Exception e) {
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005158 Log.e(TAG, "Error handling configuration change: ", e);
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005159 }
5160 }
5161
5162 private void setOrientationForAudioSystem() {
5163 switch (mDeviceOrientation) {
5164 case Configuration.ORIENTATION_LANDSCAPE:
5165 //Log.i(TAG, "orientation is landscape");
5166 AudioSystem.setParameters("orientation=landscape");
5167 break;
5168 case Configuration.ORIENTATION_PORTRAIT:
5169 //Log.i(TAG, "orientation is portrait");
5170 AudioSystem.setParameters("orientation=portrait");
5171 break;
5172 case Configuration.ORIENTATION_SQUARE:
5173 //Log.i(TAG, "orientation is square");
5174 AudioSystem.setParameters("orientation=square");
5175 break;
5176 case Configuration.ORIENTATION_UNDEFINED:
5177 //Log.i(TAG, "orientation is undefined");
5178 AudioSystem.setParameters("orientation=undefined");
5179 break;
5180 default:
5181 Log.e(TAG, "Unknown orientation");
5182 }
5183 }
5184
Jean-Michel Trivibb6f8712013-05-23 15:02:41 -07005185 private void setRotationForAudioSystem() {
5186 switch (mDeviceRotation) {
5187 case Surface.ROTATION_0:
5188 AudioSystem.setParameters("rotation=0");
5189 break;
5190 case Surface.ROTATION_90:
5191 AudioSystem.setParameters("rotation=90");
5192 break;
5193 case Surface.ROTATION_180:
5194 AudioSystem.setParameters("rotation=180");
5195 break;
5196 case Surface.ROTATION_270:
5197 AudioSystem.setParameters("rotation=270");
5198 break;
5199 default:
5200 Log.e(TAG, "Unknown device rotation");
5201 }
5202 }
5203
Jean-Michel Trivif26f0172012-04-25 16:23:20 -07005204
Eric Laurent78472112012-05-21 08:57:21 -07005205 // Handles request to override default use of A2DP for media.
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005206 // Must be called synchronized on mConnectedDevices
Eric Laurent78472112012-05-21 08:57:21 -07005207 public void setBluetoothA2dpOnInt(boolean on) {
5208 synchronized (mBluetoothA2dpEnabledLock) {
5209 mBluetoothA2dpEnabled = on;
Eric Laurentc390bed2012-07-03 12:24:05 -07005210 mAudioHandler.removeMessages(MSG_SET_FORCE_BT_A2DP_USE);
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005211 setForceUseInt_SyncDevices(AudioSystem.FOR_MEDIA,
Eric Laurentc390bed2012-07-03 12:24:05 -07005212 mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP);
Eric Laurent78472112012-05-21 08:57:21 -07005213 }
5214 }
5215
Jean-Michel Trivi7e2f3712015-01-12 11:01:55 -08005216 // Must be called synchronized on mConnectedDevices
5217 private void setForceUseInt_SyncDevices(int usage, int config) {
5218 switch (usage) {
5219 case AudioSystem.FOR_MEDIA:
5220 if (config == AudioSystem.FORCE_NO_BT_A2DP) {
5221 mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ALL_A2DP;
5222 } else { // config == AudioSystem.FORCE_NONE
5223 mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ALL_A2DP;
5224 }
5225 break;
5226 case AudioSystem.FOR_DOCK:
5227 if (config == AudioSystem.FORCE_ANALOG_DOCK) {
5228 mBecomingNoisyIntentDevices |= AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
5229 } else { // config == AudioSystem.FORCE_NONE
5230 mBecomingNoisyIntentDevices &= ~AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
5231 }
5232 break;
5233 default:
5234 // usage doesn't affect the broadcast of ACTION_AUDIO_BECOMING_NOISY
5235 }
5236 AudioSystem.setForceUse(usage, config);
5237 }
5238
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005239 @Override
Jeff Sharkey098d5802012-04-26 17:30:34 -07005240 public void setRingtonePlayer(IRingtonePlayer player) {
5241 mContext.enforceCallingOrSelfPermission(REMOTE_AUDIO_PLAYBACK, null);
5242 mRingtonePlayer = player;
5243 }
5244
5245 @Override
5246 public IRingtonePlayer getRingtonePlayer() {
5247 return mRingtonePlayer;
5248 }
5249
5250 @Override
Dianne Hackborn632ca412012-06-14 19:34:10 -07005251 public AudioRoutesInfo startWatchingRoutes(IAudioRoutesObserver observer) {
5252 synchronized (mCurAudioRoutes) {
5253 AudioRoutesInfo routes = new AudioRoutesInfo(mCurAudioRoutes);
5254 mRoutesObservers.register(observer);
5255 return routes;
5256 }
5257 }
5258
Eric Laurentc34dcc12012-09-10 13:51:52 -07005259
5260 //==========================================================================================
5261 // Safe media volume management.
5262 // MUSIC stream volume level is limited when headphones are connected according to safety
5263 // regulation. When the user attempts to raise the volume above the limit, a warning is
5264 // displayed and the user has to acknowlegde before the volume is actually changed.
5265 // The volume index corresponding to the limit is stored in config_safe_media_volume_index
5266 // property. Platforms with a different limit must set this property accordingly in their
5267 // overlay.
5268 //==========================================================================================
5269
Eric Laurentd640bd32012-09-28 18:01:48 -07005270 // mSafeMediaVolumeState indicates whether the media volume is limited over headphones.
5271 // It is SAFE_MEDIA_VOLUME_NOT_CONFIGURED at boot time until a network service is connected
5272 // or the configure time is elapsed. It is then set to SAFE_MEDIA_VOLUME_ACTIVE or
5273 // SAFE_MEDIA_VOLUME_DISABLED according to country option. If not SAFE_MEDIA_VOLUME_DISABLED, it
5274 // can be set to SAFE_MEDIA_VOLUME_INACTIVE by calling AudioService.disableSafeMediaVolume()
5275 // (when user opts out).
John Spurlock35134602014-07-24 18:10:48 -04005276 private static final int SAFE_MEDIA_VOLUME_NOT_CONFIGURED = 0;
5277 private static final int SAFE_MEDIA_VOLUME_DISABLED = 1;
5278 private static final int SAFE_MEDIA_VOLUME_INACTIVE = 2; // confirmed
5279 private static final int SAFE_MEDIA_VOLUME_ACTIVE = 3; // unconfirmed
Eric Laurentd640bd32012-09-28 18:01:48 -07005280 private Integer mSafeMediaVolumeState;
5281
5282 private int mMcc = 0;
Eric Laurentc34dcc12012-09-10 13:51:52 -07005283 // mSafeMediaVolumeIndex is the cached value of config_safe_media_volume_index property
Eric Laurentd640bd32012-09-28 18:01:48 -07005284 private int mSafeMediaVolumeIndex;
Eric Laurentc34dcc12012-09-10 13:51:52 -07005285 // mSafeMediaVolumeDevices lists the devices for which safe media volume is enforced,
5286 private final int mSafeMediaVolumeDevices = AudioSystem.DEVICE_OUT_WIRED_HEADSET |
5287 AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
5288 // mMusicActiveMs is the cumulative time of music activity since safe volume was disabled.
5289 // When this time reaches UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX, the safe media volume is re-enabled
5290 // automatically. mMusicActiveMs is rounded to a multiple of MUSIC_ACTIVE_POLL_PERIOD_MS.
5291 private int mMusicActiveMs;
5292 private static final int UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX = (20 * 3600 * 1000); // 20 hours
5293 private static final int MUSIC_ACTIVE_POLL_PERIOD_MS = 60000; // 1 minute polling interval
Eric Laurentd640bd32012-09-28 18:01:48 -07005294 private static final int SAFE_VOLUME_CONFIGURE_TIMEOUT_MS = 30000; // 30s after boot completed
Eric Laurentc34dcc12012-09-10 13:51:52 -07005295
5296 private void setSafeMediaVolumeEnabled(boolean on) {
Eric Laurentd640bd32012-09-28 18:01:48 -07005297 synchronized (mSafeMediaVolumeState) {
5298 if ((mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_NOT_CONFIGURED) &&
5299 (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_DISABLED)) {
5300 if (on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE)) {
5301 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE;
5302 enforceSafeMediaVolume();
5303 } else if (!on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE)) {
5304 mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE;
John Spurlockaa5ee4d2014-07-25 13:05:12 -04005305 mMusicActiveMs = 1; // nonzero = confirmed
5306 saveMusicActiveMs();
Eric Laurentd640bd32012-09-28 18:01:48 -07005307 sendMsg(mAudioHandler,
5308 MSG_CHECK_MUSIC_ACTIVE,
5309 SENDMSG_REPLACE,
5310 0,
5311 0,
5312 null,
5313 MUSIC_ACTIVE_POLL_PERIOD_MS);
5314 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005315 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005316 }
5317 }
5318
5319 private void enforceSafeMediaVolume() {
5320 VolumeStreamState streamState = mStreamStates[AudioSystem.STREAM_MUSIC];
Eric Laurentc34dcc12012-09-10 13:51:52 -07005321 int devices = mSafeMediaVolumeDevices;
5322 int i = 0;
5323
5324 while (devices != 0) {
5325 int device = 1 << i++;
5326 if ((device & devices) == 0) {
5327 continue;
5328 }
Eric Laurent42b041e2013-03-29 11:36:03 -07005329 int index = streamState.getIndex(device);
Eric Laurentc34dcc12012-09-10 13:51:52 -07005330 if (index > mSafeMediaVolumeIndex) {
Eric Laurent42b041e2013-03-29 11:36:03 -07005331 streamState.setIndex(mSafeMediaVolumeIndex, device);
5332 sendMsg(mAudioHandler,
5333 MSG_SET_DEVICE_VOLUME,
5334 SENDMSG_QUEUE,
5335 device,
5336 0,
5337 streamState,
5338 0);
Eric Laurentc34dcc12012-09-10 13:51:52 -07005339 }
5340 devices &= ~device;
5341 }
5342 }
5343
5344 private boolean checkSafeMediaVolume(int streamType, int index, int device) {
Eric Laurentd640bd32012-09-28 18:01:48 -07005345 synchronized (mSafeMediaVolumeState) {
5346 if ((mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) &&
Eric Laurentc34dcc12012-09-10 13:51:52 -07005347 (mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) &&
5348 ((device & mSafeMediaVolumeDevices) != 0) &&
5349 (index > mSafeMediaVolumeIndex)) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07005350 return false;
5351 }
5352 return true;
5353 }
5354 }
5355
John Spurlock3346a802014-05-20 16:25:37 -04005356 @Override
Eric Laurentc34dcc12012-09-10 13:51:52 -07005357 public void disableSafeMediaVolume() {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005358 enforceVolumeController("disable the safe media volume");
Eric Laurentd640bd32012-09-28 18:01:48 -07005359 synchronized (mSafeMediaVolumeState) {
Eric Laurentc34dcc12012-09-10 13:51:52 -07005360 setSafeMediaVolumeEnabled(false);
Eric Laurentfde16d52012-12-03 14:42:39 -08005361 if (mPendingVolumeCommand != null) {
5362 onSetStreamVolume(mPendingVolumeCommand.mStreamType,
5363 mPendingVolumeCommand.mIndex,
5364 mPendingVolumeCommand.mFlags,
5365 mPendingVolumeCommand.mDevice);
5366 mPendingVolumeCommand = null;
5367 }
Eric Laurentc34dcc12012-09-10 13:51:52 -07005368 }
5369 }
5370
Jungshik Jang41d97462014-06-30 22:26:29 +09005371 //==========================================================================================
5372 // Hdmi Cec system audio mode.
5373 // If Hdmi Cec's system audio mode is on, audio service should notify volume change
5374 // to HdmiControlService so that audio recevier can handle volume change.
5375 //==========================================================================================
5376
Eric Laurent212532b2014-07-21 15:43:18 -07005377 private class MyDisplayStatusCallback implements HdmiPlaybackClient.DisplayStatusCallback {
5378 public void onComplete(int status) {
5379 if (mHdmiManager != null) {
5380 synchronized (mHdmiManager) {
5381 mHdmiCecSink = (status != HdmiControlManager.POWER_STATUS_UNKNOWN);
5382 // Television devices without CEC service apply software volume on HDMI output
5383 if (isPlatformTelevision() && !mHdmiCecSink) {
5384 mFixedVolumeDevices &= ~AudioSystem.DEVICE_OUT_HDMI;
5385 }
5386 checkAllFixedVolumeDevices();
5387 }
5388 }
5389 }
5390 };
5391
Jungshik Jang41d97462014-06-30 22:26:29 +09005392 // If HDMI-CEC system audio is supported
5393 private boolean mHdmiSystemAudioSupported = false;
5394 // Set only when device is tv.
5395 private HdmiTvClient mHdmiTvClient;
Eric Laurent0b03f992014-11-18 18:08:02 -08005396 // true if the device has system feature PackageManager.FEATURE_LEANBACK.
Eric Laurent212532b2014-07-21 15:43:18 -07005397 // cached HdmiControlManager interface
5398 private HdmiControlManager mHdmiManager;
5399 // Set only when device is a set-top box.
5400 private HdmiPlaybackClient mHdmiPlaybackClient;
5401 // true if we are a set-top box, an HDMI sink is connected and it supports CEC.
5402 private boolean mHdmiCecSink;
5403
5404 private MyDisplayStatusCallback mHdmiDisplayStatusCallback = new MyDisplayStatusCallback();
Jungshik Jang41d97462014-06-30 22:26:29 +09005405
5406 @Override
Jungshik Jang12307ca2014-07-15 19:27:56 +09005407 public int setHdmiSystemAudioSupported(boolean on) {
Eric Laurent212532b2014-07-21 15:43:18 -07005408 int device = AudioSystem.DEVICE_NONE;
5409 if (mHdmiManager != null) {
5410 synchronized (mHdmiManager) {
5411 if (mHdmiTvClient == null) {
5412 Log.w(TAG, "Only Hdmi-Cec enabled TV device supports system audio mode.");
5413 return device;
5414 }
Jungshik Jang41d97462014-06-30 22:26:29 +09005415
Eric Laurent212532b2014-07-21 15:43:18 -07005416 synchronized (mHdmiTvClient) {
5417 if (mHdmiSystemAudioSupported != on) {
5418 mHdmiSystemAudioSupported = on;
5419 AudioSystem.setForceUse(AudioSystem.FOR_HDMI_SYSTEM_AUDIO,
5420 on ? AudioSystem.FORCE_HDMI_SYSTEM_AUDIO_ENFORCED :
5421 AudioSystem.FORCE_NONE);
5422 }
5423 device = AudioSystem.getDevicesForStream(AudioSystem.STREAM_MUSIC);
5424 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005425 }
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005426 }
Eric Laurent212532b2014-07-21 15:43:18 -07005427 return device;
Jungshik Jang6f34f5a2014-07-08 21:17:29 +09005428 }
Jungshik Jang41d97462014-06-30 22:26:29 +09005429
Terry Heoe7d6d972014-09-04 21:05:28 +09005430 @Override
5431 public boolean isHdmiSystemAudioSupported() {
5432 return mHdmiSystemAudioSupported;
5433 }
5434
Eric Laurentdd45d012012-10-08 09:04:34 -07005435 //==========================================================================================
Jean-Michel Trivi873cc452014-09-11 17:25:09 -07005436 // Accessibility: taking touch exploration into account for selecting the default
5437 // stream override timeout when adjusting volume
5438 //==========================================================================================
5439 private static class StreamOverride
5440 implements AccessibilityManager.TouchExplorationStateChangeListener {
5441
5442 // AudioService.getActiveStreamType() will return:
5443 // - STREAM_NOTIFICATION on tablets during this period after a notification stopped
5444 // - STREAM_MUSIC on phones during this period after music or talkback/voice search prompt
5445 // stopped
5446 private static final int DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS = 5000;
5447 private static final int TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS = 1000;
5448
5449 static int sDelayMs;
5450
5451 static void init(Context ctxt) {
5452 AccessibilityManager accessibilityManager =
5453 (AccessibilityManager) ctxt.getSystemService(Context.ACCESSIBILITY_SERVICE);
5454 updateDefaultStreamOverrideDelay(
5455 accessibilityManager.isTouchExplorationEnabled());
5456 accessibilityManager.addTouchExplorationStateChangeListener(
5457 new StreamOverride());
5458 }
5459
5460 @Override
5461 public void onTouchExplorationStateChanged(boolean enabled) {
5462 updateDefaultStreamOverrideDelay(enabled);
5463 }
5464
5465 private static void updateDefaultStreamOverrideDelay(boolean touchExploreEnabled) {
5466 if (touchExploreEnabled) {
5467 sDelayMs = TOUCH_EXPLORE_STREAM_TYPE_OVERRIDE_DELAY_MS;
5468 } else {
5469 sDelayMs = DEFAULT_STREAM_TYPE_OVERRIDE_DELAY_MS;
5470 }
5471 if (DEBUG_VOL) Log.d(TAG, "Touch exploration enabled=" + touchExploreEnabled
5472 + " stream override delay is now " + sDelayMs + " ms");
5473 }
5474 }
5475
5476 //==========================================================================================
Eric Laurentdd45d012012-10-08 09:04:34 -07005477 // Camera shutter sound policy.
5478 // config_camera_sound_forced configuration option in config.xml defines if the camera shutter
5479 // sound is forced (sound even if the device is in silent mode) or not. This option is false by
5480 // default and can be overridden by country specific overlay in values-mccXXX/config.xml.
5481 //==========================================================================================
5482
5483 // cached value of com.android.internal.R.bool.config_camera_sound_forced
5484 private Boolean mCameraSoundForced;
5485
5486 // called by android.hardware.Camera to populate CameraInfo.canDisableShutterSound
5487 public boolean isCameraSoundForced() {
5488 synchronized (mCameraSoundForced) {
5489 return mCameraSoundForced;
5490 }
5491 }
5492
5493 private static final String[] RINGER_MODE_NAMES = new String[] {
5494 "SILENT",
5495 "VIBRATE",
5496 "NORMAL"
5497 };
5498
5499 private void dumpRingerMode(PrintWriter pw) {
5500 pw.println("\nRinger mode: ");
John Spurlock661f2cf2014-11-17 10:29:10 -05005501 pw.println("- mode (internal) = " + RINGER_MODE_NAMES[mRingerMode]);
5502 pw.println("- mode (external) = " + RINGER_MODE_NAMES[mRingerModeExternal]);
Eric Laurentdd45d012012-10-08 09:04:34 -07005503 pw.print("- ringer mode affected streams = 0x");
5504 pw.println(Integer.toHexString(mRingerModeAffectedStreams));
5505 pw.print("- ringer mode muted streams = 0x");
5506 pw.println(Integer.toHexString(mRingerModeMutedStreams));
John Spurlock661f2cf2014-11-17 10:29:10 -05005507 pw.print("- delegate = "); pw.println(mRingerModeDelegate);
Eric Laurentdd45d012012-10-08 09:04:34 -07005508 }
5509
Dianne Hackborn632ca412012-06-14 19:34:10 -07005510 @Override
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005511 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyeb4cc4922012-04-26 18:17:29 -07005512 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
5513
Jean-Michel Trivifa9a6982013-06-27 16:22:58 -07005514 mMediaFocusControl.dump(pw);
Eric Laurentbffc3d12012-05-07 17:43:49 -07005515 dumpStreamStates(pw);
Eric Laurentdd45d012012-10-08 09:04:34 -07005516 dumpRingerMode(pw);
Dianne Hackborn632ca412012-06-14 19:34:10 -07005517 pw.println("\nAudio routes:");
John Spurlock61560172015-02-06 19:46:04 -05005518 pw.print(" mMainType=0x"); pw.println(Integer.toHexString(mCurAudioRoutes.mainType));
5519 pw.print(" mBluetoothName="); pw.println(mCurAudioRoutes.bluetoothName);
John Spurlock35134602014-07-24 18:10:48 -04005520
5521 pw.println("\nOther state:");
John Spurlock3346a802014-05-20 16:25:37 -04005522 pw.print(" mVolumeController="); pw.println(mVolumeController);
John Spurlock35134602014-07-24 18:10:48 -04005523 pw.print(" mSafeMediaVolumeState=");
5524 pw.println(safeMediaVolumeStateToString(mSafeMediaVolumeState));
5525 pw.print(" mSafeMediaVolumeIndex="); pw.println(mSafeMediaVolumeIndex);
5526 pw.print(" mPendingVolumeCommand="); pw.println(mPendingVolumeCommand);
5527 pw.print(" mMusicActiveMs="); pw.println(mMusicActiveMs);
John Spurlockaa5ee4d2014-07-25 13:05:12 -04005528 pw.print(" mMcc="); pw.println(mMcc);
John Spurlock5e783732015-02-19 10:28:59 -05005529 pw.print(" mCameraSoundForced="); pw.println(mCameraSoundForced);
John Spurlock661f2cf2014-11-17 10:29:10 -05005530 pw.print(" mHasVibrator="); pw.println(mHasVibrator);
John Spurlockcdb57ae2015-02-11 19:04:11 -05005531 pw.print(" mControllerService="); pw.println(mControllerService);
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005532
5533 dumpAudioPolicies(pw);
John Spurlock35134602014-07-24 18:10:48 -04005534 }
5535
5536 private static String safeMediaVolumeStateToString(Integer state) {
5537 switch(state) {
5538 case SAFE_MEDIA_VOLUME_NOT_CONFIGURED: return "SAFE_MEDIA_VOLUME_NOT_CONFIGURED";
5539 case SAFE_MEDIA_VOLUME_DISABLED: return "SAFE_MEDIA_VOLUME_DISABLED";
5540 case SAFE_MEDIA_VOLUME_INACTIVE: return "SAFE_MEDIA_VOLUME_INACTIVE";
5541 case SAFE_MEDIA_VOLUME_ACTIVE: return "SAFE_MEDIA_VOLUME_ACTIVE";
5542 }
5543 return null;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08005544 }
Glenn Kastenfd116ad2013-07-12 17:10:39 -07005545
5546 // Inform AudioFlinger of our device's low RAM attribute
5547 private static void readAndSetLowRamDevice()
5548 {
5549 int status = AudioSystem.setLowRamDevice(ActivityManager.isLowRamDeviceStatic());
5550 if (status != 0) {
5551 Log.w(TAG, "AudioFlinger informed of device's low RAM attribute; status " + status);
5552 }
5553 }
John Spurlock3346a802014-05-20 16:25:37 -04005554
John Spurlockcdb57ae2015-02-11 19:04:11 -05005555 private void enforceVolumeController(String action) {
5556 if (mControllerService.mUid != 0 && Binder.getCallingUid() == mControllerService.mUid) {
5557 return;
5558 }
John Spurlock3346a802014-05-20 16:25:37 -04005559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
5560 "Only SystemUI can " + action);
5561 }
5562
5563 @Override
5564 public void setVolumeController(final IVolumeController controller) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005565 enforceVolumeController("set the volume controller");
John Spurlock3346a802014-05-20 16:25:37 -04005566
5567 // return early if things are not actually changing
5568 if (mVolumeController.isSameBinder(controller)) {
5569 return;
5570 }
5571
5572 // dismiss the old volume controller
5573 mVolumeController.postDismiss();
5574 if (controller != null) {
5575 // we are about to register a new controller, listen for its death
5576 try {
5577 controller.asBinder().linkToDeath(new DeathRecipient() {
5578 @Override
5579 public void binderDied() {
5580 if (mVolumeController.isSameBinder(controller)) {
5581 Log.w(TAG, "Current remote volume controller died, unregistering");
5582 setVolumeController(null);
5583 }
5584 }
5585 }, 0);
5586 } catch (RemoteException e) {
5587 // noop
5588 }
5589 }
5590 mVolumeController.setController(controller);
John Spurlock33f4e042014-07-11 13:10:58 -04005591 if (DEBUG_VOL) Log.d(TAG, "Volume controller: " + mVolumeController);
5592 }
5593
5594 @Override
5595 public void notifyVolumeControllerVisible(final IVolumeController controller, boolean visible) {
John Spurlockcdb57ae2015-02-11 19:04:11 -05005596 enforceVolumeController("notify about volume controller visibility");
John Spurlock33f4e042014-07-11 13:10:58 -04005597
5598 // return early if the controller is not current
5599 if (!mVolumeController.isSameBinder(controller)) {
5600 return;
5601 }
5602
5603 mVolumeController.setVisible(visible);
5604 if (DEBUG_VOL) Log.d(TAG, "Volume controller visible: " + visible);
John Spurlock3346a802014-05-20 16:25:37 -04005605 }
RoboErikd09bd0c2014-06-24 17:45:19 -07005606
5607 public static class VolumeController {
5608 private static final String TAG = "VolumeController";
5609
5610 private IVolumeController mController;
John Spurlock33f4e042014-07-11 13:10:58 -04005611 private boolean mVisible;
5612 private long mNextLongPress;
5613 private int mLongPressTimeout;
RoboErikd09bd0c2014-06-24 17:45:19 -07005614
5615 public void setController(IVolumeController controller) {
5616 mController = controller;
John Spurlock33f4e042014-07-11 13:10:58 -04005617 mVisible = false;
5618 }
5619
5620 public void loadSettings(ContentResolver cr) {
5621 mLongPressTimeout = Settings.Secure.getIntForUser(cr,
5622 Settings.Secure.LONG_PRESS_TIMEOUT, 500, UserHandle.USER_CURRENT);
5623 }
5624
RoboErik4197cb62015-01-21 15:45:32 -08005625 public boolean suppressAdjustment(int resolvedStream, int flags, boolean isMute) {
5626 if (isMute) {
5627 return false;
5628 }
John Spurlock33f4e042014-07-11 13:10:58 -04005629 boolean suppress = false;
5630 if (resolvedStream == AudioSystem.STREAM_RING && mController != null) {
5631 final long now = SystemClock.uptimeMillis();
5632 if ((flags & AudioManager.FLAG_SHOW_UI) != 0 && !mVisible) {
5633 // ui will become visible
5634 if (mNextLongPress < now) {
5635 mNextLongPress = now + mLongPressTimeout;
5636 }
5637 suppress = true;
5638 } else if (mNextLongPress > 0) { // in a long-press
5639 if (now > mNextLongPress) {
5640 // long press triggered, no more suppression
5641 mNextLongPress = 0;
5642 } else {
5643 // keep suppressing until the long press triggers
5644 suppress = true;
5645 }
5646 }
5647 }
5648 return suppress;
5649 }
5650
5651 public void setVisible(boolean visible) {
5652 mVisible = visible;
RoboErikd09bd0c2014-06-24 17:45:19 -07005653 }
5654
5655 public boolean isSameBinder(IVolumeController controller) {
5656 return Objects.equals(asBinder(), binder(controller));
5657 }
5658
5659 public IBinder asBinder() {
5660 return binder(mController);
5661 }
5662
5663 private static IBinder binder(IVolumeController controller) {
5664 return controller == null ? null : controller.asBinder();
5665 }
5666
5667 @Override
5668 public String toString() {
John Spurlock33f4e042014-07-11 13:10:58 -04005669 return "VolumeController(" + asBinder() + ",mVisible=" + mVisible + ")";
RoboErikd09bd0c2014-06-24 17:45:19 -07005670 }
5671
5672 public void postDisplaySafeVolumeWarning(int flags) {
5673 if (mController == null)
5674 return;
5675 try {
5676 mController.displaySafeVolumeWarning(flags);
5677 } catch (RemoteException e) {
5678 Log.w(TAG, "Error calling displaySafeVolumeWarning", e);
5679 }
5680 }
5681
5682 public void postVolumeChanged(int streamType, int flags) {
5683 if (mController == null)
5684 return;
5685 try {
5686 mController.volumeChanged(streamType, flags);
5687 } catch (RemoteException e) {
5688 Log.w(TAG, "Error calling volumeChanged", e);
5689 }
5690 }
5691
5692 public void postMasterVolumeChanged(int flags) {
5693 if (mController == null)
5694 return;
5695 try {
5696 mController.masterVolumeChanged(flags);
5697 } catch (RemoteException e) {
5698 Log.w(TAG, "Error calling masterVolumeChanged", e);
5699 }
5700 }
5701
5702 public void postMasterMuteChanged(int flags) {
5703 if (mController == null)
5704 return;
5705 try {
5706 mController.masterMuteChanged(flags);
5707 } catch (RemoteException e) {
5708 Log.w(TAG, "Error calling masterMuteChanged", e);
5709 }
5710 }
5711
5712 public void setLayoutDirection(int layoutDirection) {
5713 if (mController == null)
5714 return;
5715 try {
5716 mController.setLayoutDirection(layoutDirection);
5717 } catch (RemoteException e) {
5718 Log.w(TAG, "Error calling setLayoutDirection", e);
5719 }
5720 }
5721
5722 public void postDismiss() {
5723 if (mController == null)
5724 return;
5725 try {
5726 mController.dismiss();
5727 } catch (RemoteException e) {
5728 Log.w(TAG, "Error calling dismiss", e);
5729 }
5730 }
5731 }
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005732
RoboErik0dac35a2014-08-12 15:48:49 -07005733 /**
5734 * Interface for system components to get some extra functionality through
5735 * LocalServices.
5736 */
5737 final class AudioServiceInternal extends AudioManagerInternal {
John Spurlock661f2cf2014-11-17 10:29:10 -05005738 @Override
5739 public void setRingerModeDelegate(RingerModeDelegate delegate) {
5740 mRingerModeDelegate = delegate;
5741 if (mRingerModeDelegate != null) {
5742 setRingerModeInternal(getRingerModeInternal(), TAG + ".setRingerModeDelegate");
5743 }
5744 }
RoboErik272e1612014-09-05 11:39:29 -07005745
5746 @Override
5747 public void adjustSuggestedStreamVolumeForUid(int streamType, int direction, int flags,
5748 String callingPackage, int uid) {
5749 // direction and stream type swap here because the public
5750 // adjustSuggested has a different order than the other methods.
5751 adjustSuggestedStreamVolume(direction, streamType, flags, callingPackage, uid);
5752 }
5753
RoboErik0dac35a2014-08-12 15:48:49 -07005754 @Override
5755 public void adjustStreamVolumeForUid(int streamType, int direction, int flags,
5756 String callingPackage, int uid) {
5757 adjustStreamVolume(streamType, direction, flags, callingPackage, uid);
5758 }
5759
5760 @Override
5761 public void setStreamVolumeForUid(int streamType, int direction, int flags,
5762 String callingPackage, int uid) {
5763 setStreamVolume(streamType, direction, flags, callingPackage, uid);
5764 }
RoboErik519c7742014-11-18 10:59:09 -08005765
5766 @Override
5767 public void adjustMasterVolumeForUid(int steps, int flags, String callingPackage,
5768 int uid) {
5769 adjustMasterVolume(steps, flags, callingPackage, uid);
5770 }
John Spurlock661f2cf2014-11-17 10:29:10 -05005771
5772 @Override
5773 public int getRingerModeInternal() {
5774 return AudioService.this.getRingerModeInternal();
5775 }
5776
5777 @Override
5778 public void setRingerModeInternal(int ringerMode, String caller) {
5779 AudioService.this.setRingerModeInternal(ringerMode, caller);
5780 }
John Spurlockcdb57ae2015-02-11 19:04:11 -05005781
5782 @Override
5783 public int getVolumeControllerUid() {
5784 return mControllerService.mUid;
5785 }
RoboErik0dac35a2014-08-12 15:48:49 -07005786 }
5787
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005788 //==========================================================================================
5789 // Audio policy management
5790 //==========================================================================================
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005791 public String registerAudioPolicy(AudioPolicyConfig policyConfig, IAudioPolicyCallback pcb,
5792 boolean hasFocusListener) {
5793 if (DEBUG_AP) Log.d(TAG, "registerAudioPolicy for " + pcb.asBinder()
5794 + " with config:" + policyConfig);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005795 String regId = null;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005796 // error handling
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005797 boolean hasPermissionForPolicy =
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005798 (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission(
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005799 android.Manifest.permission.MODIFY_AUDIO_ROUTING));
5800 if (!hasPermissionForPolicy) {
5801 Slog.w(TAG, "Can't register audio policy for pid " + Binder.getCallingPid() + " / uid "
5802 + Binder.getCallingUid() + ", need MODIFY_AUDIO_ROUTING");
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005803 return null;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005804 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005805
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005806 synchronized (mAudioPolicies) {
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005807 try {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005808 if (mAudioPolicies.containsKey(pcb.asBinder())) {
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005809 Slog.e(TAG, "Cannot re-register policy");
5810 return null;
5811 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005812 AudioPolicyProxy app = new AudioPolicyProxy(policyConfig, pcb, hasFocusListener);
5813 pcb.asBinder().linkToDeath(app, 0/*flags*/);
5814 regId = app.getRegistrationId();
5815 mAudioPolicies.put(pcb.asBinder(), app);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005816 } catch (RemoteException e) {
5817 // audio policy owner has already died!
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005818 Slog.w(TAG, "Audio policy registration failed, could not link to " + pcb +
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005819 " binder death", e);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005820 return null;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005821 }
5822 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005823 return regId;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005824 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005825
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005826 public void unregisterAudioPolicyAsync(IAudioPolicyCallback pcb) {
5827 if (DEBUG_AP) Log.d(TAG, "unregisterAudioPolicyAsync for " + pcb.asBinder());
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005828 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005829 AudioPolicyProxy app = mAudioPolicies.remove(pcb.asBinder());
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005830 if (app == null) {
5831 Slog.w(TAG, "Trying to unregister unknown audio policy for pid "
5832 + Binder.getCallingPid() + " / uid " + Binder.getCallingUid());
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005833 return;
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005834 } else {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005835 pcb.asBinder().unlinkToDeath(app, 0/*flags*/);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005836 }
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005837 app.release();
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005838 }
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005839 // TODO implement clearing mix attribute matching info in native audio policy
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005840 }
5841
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005842 public int setFocusPropertiesForPolicy(int duckingBehavior, IAudioPolicyCallback pcb) {
5843 if (DEBUG_AP) Log.d(TAG, "setFocusPropertiesForPolicy() duck behavior=" + duckingBehavior
5844 + " policy " + pcb.asBinder());
5845 // error handling
5846 boolean hasPermissionForPolicy =
5847 (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission(
5848 android.Manifest.permission.MODIFY_AUDIO_ROUTING));
5849 if (!hasPermissionForPolicy) {
5850 Slog.w(TAG, "Cannot change audio policy ducking handling for pid " +
5851 + Binder.getCallingPid() + " / uid "
5852 + Binder.getCallingUid() + ", need MODIFY_AUDIO_ROUTING");
5853 return AudioManager.ERROR;
5854 }
5855
5856 synchronized (mAudioPolicies) {
5857 if (!mAudioPolicies.containsKey(pcb.asBinder())) {
5858 Slog.e(TAG, "Cannot change audio policy focus properties, unregistered policy");
5859 return AudioManager.ERROR;
5860 }
5861 final AudioPolicyProxy app = mAudioPolicies.get(pcb.asBinder());
5862 if (duckingBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5863 // is there already one policy managing ducking?
5864 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
5865 if (policy.mFocusDuckBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5866 Slog.e(TAG, "Cannot change audio policy ducking behavior, already handled");
5867 return AudioManager.ERROR;
5868 }
5869 }
5870 }
5871 app.mFocusDuckBehavior = duckingBehavior;
5872 mMediaFocusControl.setDuckingInExtPolicyAvailable(
5873 duckingBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY);
5874 }
5875 return AudioManager.SUCCESS;
5876 }
5877
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005878 private void dumpAudioPolicies(PrintWriter pw) {
5879 pw.println("\nAudio policies:");
5880 synchronized (mAudioPolicies) {
5881 for(AudioPolicyProxy policy : mAudioPolicies.values()) {
5882 pw.println(policy.toLogFriendlyString());
5883 }
5884 }
5885 }
5886
Jean-Michel Trivi958876f2014-11-16 15:40:22 -08005887 //======================
5888 // Audio policy proxy
5889 //======================
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005890 /**
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005891 * This internal class inherits from AudioPolicyConfig, each instance contains all the
5892 * mixes of an AudioPolicy and their configurations.
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005893 */
5894 public class AudioPolicyProxy extends AudioPolicyConfig implements IBinder.DeathRecipient {
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005895 private static final String TAG = "AudioPolicyProxy";
5896 AudioPolicyConfig mConfig;
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005897 IAudioPolicyCallback mPolicyToken;
5898 boolean mHasFocusListener;
5899 /**
5900 * Audio focus ducking behavior for an audio policy.
5901 * This variable reflects the value that was successfully set in
5902 * {@link AudioService#setFocusPropertiesForPolicy(int, IAudioPolicyCallback)}. This
5903 * implies that a value of FOCUS_POLICY_DUCKING_IN_POLICY means the corresponding policy
5904 * is handling ducking for audio focus.
5905 */
5906 int mFocusDuckBehavior = AudioPolicy.FOCUS_POLICY_DUCKING_DEFAULT;
5907
5908 AudioPolicyProxy(AudioPolicyConfig config, IAudioPolicyCallback token,
5909 boolean hasFocusListener) {
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005910 super(config);
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005911 setRegistration(new String(config.hashCode() + ":ap:" + mAudioPolicyCounter++));
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005912 mPolicyToken = token;
5913 mHasFocusListener = hasFocusListener;
5914 if (mHasFocusListener) {
5915 mMediaFocusControl.addFocusFollower(mPolicyToken);
5916 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005917 connectMixes();
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005918 }
5919
5920 public void binderDied() {
5921 synchronized (mAudioPolicies) {
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005922 Log.i(TAG, "audio policy " + mPolicyToken + " died");
5923 release();
5924 mAudioPolicies.remove(mPolicyToken.asBinder());
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005925 }
5926 }
5927
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005928 String getRegistrationId() {
Jean-Michel Trivi1b3541d2014-11-25 12:53:41 -08005929 return getRegistration();
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005930 }
5931
Jean-Michel Trivi0212be52014-11-24 14:43:10 -08005932 void release() {
5933 if (mFocusDuckBehavior == AudioPolicy.FOCUS_POLICY_DUCKING_IN_POLICY) {
5934 mMediaFocusControl.setDuckingInExtPolicyAvailable(false);
5935 }
5936 if (mHasFocusListener) {
5937 mMediaFocusControl.removeFocusFollower(mPolicyToken);
5938 }
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005939 AudioSystem.registerPolicyMixes(mMixes, false);
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005940 }
5941
Eric Laurent7f5eb9f2014-12-01 19:36:30 -08005942 void connectMixes() {
5943 AudioSystem.registerPolicyMixes(mMixes, true);
Jean-Michel Trivia8b6bd82014-07-01 09:48:46 -07005944 }
5945 };
5946
5947 private HashMap<IBinder, AudioPolicyProxy> mAudioPolicies =
5948 new HashMap<IBinder, AudioPolicyProxy>();
Jean-Michel Trivi8fdb0d42014-07-16 19:08:37 -07005949 private int mAudioPolicyCounter = 0; // always accessed synchronized on mAudioPolicies
John Spurlockcdb57ae2015-02-11 19:04:11 -05005950
5951 private class ControllerService extends ContentObserver {
5952 private int mUid;
5953 private ComponentName mComponent;
5954
5955 public ControllerService() {
5956 super(null);
5957 }
5958
5959 @Override
5960 public String toString() {
5961 return String.format("{mUid=%d,mComponent=%s}", mUid, mComponent);
5962 }
5963
5964 public void init() {
5965 onChange(true);
5966 mContentResolver.registerContentObserver(Settings.Secure.getUriFor(
5967 Settings.Secure.VOLUME_CONTROLLER_SERVICE_COMPONENT), false, this);
5968 }
5969
5970 @Override
5971 public void onChange(boolean selfChange) {
5972 mUid = 0;
5973 mComponent = null;
5974 final String setting = Settings.Secure.getString(mContentResolver,
5975 Settings.Secure.VOLUME_CONTROLLER_SERVICE_COMPONENT);
5976 if (setting == null) return;
5977 try {
5978 mComponent = ComponentName.unflattenFromString(setting);
5979 if (mComponent == null) return;
5980 mUid = mContext.getPackageManager()
5981 .getApplicationInfo(mComponent.getPackageName(), 0).uid;
5982 } catch (Exception e) {
5983 Log.w(TAG, "Error loading controller service", e);
5984 }
5985 if (DEBUG_VOL) Log.d(TAG, "Reloaded controller service: " + this);
5986 }
5987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988}