AppRTCAudioManager.java

  1/*
  2 *  Copyright 2014 The WebRTC Project Authors. All rights reserved.
  3 *
  4 *  Use of this source code is governed by a BSD-style license
  5 *  that can be found in the LICENSE file in the root of the source
  6 *  tree. An additional intellectual property rights grant can be found
  7 *  in the file PATENTS.  All contributing project authors may
  8 *  be found in the AUTHORS file in the root of the source tree.
  9 */
 10package eu.siacs.conversations.services;
 11
 12import android.content.BroadcastReceiver;
 13import android.content.Context;
 14import android.content.Intent;
 15import android.content.IntentFilter;
 16import android.content.pm.PackageManager;
 17import android.media.AudioDeviceInfo;
 18import android.media.AudioFormat;
 19import android.media.AudioManager;
 20import android.media.AudioRecord;
 21import android.media.MediaRecorder;
 22import android.os.Build;
 23import android.util.Log;
 24
 25import androidx.annotation.Nullable;
 26
 27import org.webrtc.ThreadUtils;
 28
 29import java.util.Collections;
 30import java.util.HashSet;
 31import java.util.Set;
 32import java.util.concurrent.CountDownLatch;
 33
 34import eu.siacs.conversations.Config;
 35import eu.siacs.conversations.utils.AppRTCUtils;
 36import eu.siacs.conversations.xmpp.jingle.Media;
 37
 38/**
 39 * AppRTCAudioManager manages all audio related parts of the AppRTC demo.
 40 */
 41public class AppRTCAudioManager {
 42
 43    private static CountDownLatch microphoneLatch;
 44
 45    private final Context apprtcContext;
 46    // Contains speakerphone setting: auto, true or false
 47    @Nullable
 48    private SpeakerPhonePreference speakerPhonePreference;
 49    // Handles all tasks related to Bluetooth headset devices.
 50    private final AppRTCBluetoothManager bluetoothManager;
 51    @Nullable
 52    private final AudioManager audioManager;
 53    @Nullable
 54    private AudioManagerEvents audioManagerEvents;
 55    private AudioManagerState amState;
 56    private boolean savedIsSpeakerPhoneOn;
 57    private boolean savedIsMicrophoneMute;
 58    private boolean hasWiredHeadset;
 59    // Default audio device; speaker phone for video calls or earpiece for audio
 60    // only calls.
 61    private AudioDevice defaultAudioDevice;
 62    // Contains the currently selected audio device.
 63    // This device is changed automatically using a certain scheme where e.g.
 64    // a wired headset "wins" over speaker phone. It is also possible for a
 65    // user to explicitly select a device (and overrid any predefined scheme).
 66    // See |userSelectedAudioDevice| for details.
 67    private AudioDevice selectedAudioDevice;
 68    // Contains the user-selected audio device which overrides the predefined
 69    // selection scheme.
 70    // TODO(henrika): always set to AudioDevice.NONE today. Add support for
 71    // explicit selection based on choice by userSelectedAudioDevice.
 72    private AudioDevice userSelectedAudioDevice;
 73    // Proximity sensor object. It measures the proximity of an object in cm
 74    // relative to the view screen of a device and can therefore be used to
 75    // assist device switching (close to ear <=> use headset earpiece if
 76    // available, far from ear <=> use speaker phone).
 77    @Nullable
 78    private AppRTCProximitySensor proximitySensor;
 79    // Contains a list of available audio devices. A Set collection is used to
 80    // avoid duplicate elements.
 81    private Set<AudioDevice> audioDevices = new HashSet<>();
 82    // Broadcast receiver for wired headset intent broadcasts.
 83    private final BroadcastReceiver wiredHeadsetReceiver;
 84    // Callback method for changes in audio focus.
 85    @Nullable
 86    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;
 87
 88    private AppRTCAudioManager(Context context, final SpeakerPhonePreference speakerPhonePreference) {
 89        Log.d(Config.LOGTAG, "ctor");
 90        ThreadUtils.checkIsOnMainThread();
 91        apprtcContext = context;
 92        audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));
 93        bluetoothManager = AppRTCBluetoothManager.create(context, this);
 94        wiredHeadsetReceiver = new WiredHeadsetReceiver();
 95        amState = AudioManagerState.UNINITIALIZED;
 96        this.speakerPhonePreference = speakerPhonePreference;
 97        if (speakerPhonePreference == SpeakerPhonePreference.EARPIECE && hasEarpiece()) {
 98            defaultAudioDevice = AudioDevice.EARPIECE;
 99        } else {
100            defaultAudioDevice = AudioDevice.SPEAKER_PHONE;
101        }
102        // Create and initialize the proximity sensor.
103        // Tablet devices (e.g. Nexus 7) does not support proximity sensors.
104        // Note that, the sensor will not be active until start() has been called.
105        proximitySensor = AppRTCProximitySensor.create(context,
106                // This method will be called each time a state change is detected.
107                // Example: user holds his hand over the device (closer than ~5 cm),
108                // or removes his hand from the device.
109                this::onProximitySensorChangedState);
110        Log.d(Config.LOGTAG, "defaultAudioDevice: " + defaultAudioDevice);
111        AppRTCUtils.logDeviceInfo(Config.LOGTAG);
112    }
113
114    public void switchSpeakerPhonePreference(final SpeakerPhonePreference speakerPhonePreference) {
115        this.speakerPhonePreference = speakerPhonePreference;
116        if (speakerPhonePreference == SpeakerPhonePreference.EARPIECE && hasEarpiece()) {
117            defaultAudioDevice = AudioDevice.EARPIECE;
118        } else {
119            defaultAudioDevice = AudioDevice.SPEAKER_PHONE;
120        }
121        updateAudioDeviceState();
122    }
123
124    /**
125     * Construction.
126     */
127    public static AppRTCAudioManager create(Context context, SpeakerPhonePreference speakerPhonePreference) {
128        return new AppRTCAudioManager(context, speakerPhonePreference);
129    }
130
131    public static boolean isMicrophoneAvailable() {
132        microphoneLatch = new CountDownLatch(1);
133        AudioRecord audioRecord = null;
134        boolean available = true;
135        try {
136            final int sampleRate = 44100;
137            final int channel = AudioFormat.CHANNEL_IN_MONO;
138            final int format = AudioFormat.ENCODING_PCM_16BIT;
139            final int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channel, format);
140            audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channel, format, bufferSize);
141            audioRecord.startRecording();
142            final short[] buffer = new short[bufferSize];
143            final int audioStatus = audioRecord.read(buffer, 0, bufferSize);
144            if (audioStatus == AudioRecord.ERROR_INVALID_OPERATION || audioStatus == AudioRecord.STATE_UNINITIALIZED)
145                available = false;
146        } catch (Exception e) {
147            available = false;
148        } finally {
149            release(audioRecord);
150
151        }
152        microphoneLatch.countDown();
153        return available;
154    }
155
156    private static void release(final AudioRecord audioRecord) {
157        if (audioRecord == null) {
158            return;
159        }
160        try {
161            audioRecord.release();
162        } catch (Exception e) {
163            //ignore
164        }
165    }
166
167    /**
168     * This method is called when the proximity sensor reports a state change,
169     * e.g. from "NEAR to FAR" or from "FAR to NEAR".
170     */
171    private void onProximitySensorChangedState() {
172        if (speakerPhonePreference != SpeakerPhonePreference.AUTO) {
173            return;
174        }
175        // The proximity sensor should only be activated when there are exactly two
176        // available audio devices.
177        if (audioDevices.size() == 2 && audioDevices.contains(AppRTCAudioManager.AudioDevice.EARPIECE)
178                && audioDevices.contains(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE)) {
179            if (proximitySensor.sensorReportsNearState()) {
180                // Sensor reports that a "handset is being held up to a person's ear",
181                // or "something is covering the light sensor".
182                setAudioDeviceInternal(AppRTCAudioManager.AudioDevice.EARPIECE);
183            } else {
184                // Sensor reports that a "handset is removed from a person's ear", or
185                // "the light sensor is no longer covered".
186                setAudioDeviceInternal(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
187            }
188        }
189    }
190
191    @SuppressWarnings("deprecation")
192    public void start(AudioManagerEvents audioManagerEvents) {
193        Log.d(Config.LOGTAG, AppRTCAudioManager.class.getName() + ".start()");
194        ThreadUtils.checkIsOnMainThread();
195        if (amState == AudioManagerState.RUNNING) {
196            Log.e(Config.LOGTAG, "AudioManager is already active");
197            return;
198        }
199        awaitMicrophoneLatch();
200        this.audioManagerEvents = audioManagerEvents;
201        amState = AudioManagerState.RUNNING;
202        // Store current audio state so we can restore it when stop() is called.
203        savedIsSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
204        savedIsMicrophoneMute = audioManager.isMicrophoneMute();
205        hasWiredHeadset = hasWiredHeadset();
206        // Create an AudioManager.OnAudioFocusChangeListener instance.
207        audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
208            // Called on the listener to notify if the audio focus for this listener has been changed.
209            // The |focusChange| value indicates whether the focus was gained, whether the focus was lost,
210            // and whether that loss is transient, or whether the new focus holder will hold it for an
211            // unknown amount of time.
212            // TODO(henrika): possibly extend support of handling audio-focus changes. Only contains
213            // logging for now.
214            @Override
215            public void onAudioFocusChange(int focusChange) {
216                final String typeOfChange;
217                switch (focusChange) {
218                    case AudioManager.AUDIOFOCUS_GAIN:
219                        typeOfChange = "AUDIOFOCUS_GAIN";
220                        break;
221                    case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
222                        typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT";
223                        break;
224                    case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE:
225                        typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE";
226                        break;
227                    case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
228                        typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK";
229                        break;
230                    case AudioManager.AUDIOFOCUS_LOSS:
231                        typeOfChange = "AUDIOFOCUS_LOSS";
232                        break;
233                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
234                        typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT";
235                        break;
236                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
237                        typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK";
238                        break;
239                    default:
240                        typeOfChange = "AUDIOFOCUS_INVALID";
241                        break;
242                }
243                Log.d(Config.LOGTAG, "onAudioFocusChange: " + typeOfChange);
244            }
245        };
246        // Request audio playout focus (without ducking) and install listener for changes in focus.
247        int result = audioManager.requestAudioFocus(audioFocusChangeListener,
248                AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
249        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
250            Log.d(Config.LOGTAG, "Audio focus request granted for VOICE_CALL streams");
251        } else {
252            Log.e(Config.LOGTAG, "Audio focus request failed");
253        }
254        // Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
255        // required to be in this mode when playout and/or recording starts for
256        // best possible VoIP performance.
257        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
258        // Always disable microphone mute during a WebRTC call.
259        setMicrophoneMute(false);
260        // Set initial device states.
261        userSelectedAudioDevice = AudioDevice.NONE;
262        selectedAudioDevice = AudioDevice.NONE;
263        audioDevices.clear();
264        // Initialize and start Bluetooth if a BT device is available or initiate
265        // detection of new (enabled) BT devices.
266        bluetoothManager.start();
267        // Do initial selection of audio device. This setting can later be changed
268        // either by adding/removing a BT or wired headset or by covering/uncovering
269        // the proximity sensor.
270        updateAudioDeviceState();
271        // Register receiver for broadcast intents related to adding/removing a
272        // wired headset.
273        registerReceiver(wiredHeadsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
274        Log.d(Config.LOGTAG, "AudioManager started");
275    }
276
277    private void awaitMicrophoneLatch() {
278        final CountDownLatch latch = microphoneLatch;
279        if (latch == null) {
280            return;
281        }
282        try {
283            latch.await();
284        } catch (InterruptedException e) {
285            //ignore
286        }
287    }
288
289    @SuppressWarnings("deprecation")
290    public void stop() {
291        Log.d(Config.LOGTAG, AppRTCAudioManager.class.getName() + ".stop()");
292        ThreadUtils.checkIsOnMainThread();
293        if (amState != AudioManagerState.RUNNING) {
294            Log.e(Config.LOGTAG, "Trying to stop AudioManager in incorrect state: " + amState);
295            return;
296        }
297        amState = AudioManagerState.UNINITIALIZED;
298        unregisterReceiver(wiredHeadsetReceiver);
299        bluetoothManager.stop();
300        // Restore previously stored audio states.
301        setSpeakerphoneOn(savedIsSpeakerPhoneOn);
302        setMicrophoneMute(savedIsMicrophoneMute);
303        audioManager.setMode(AudioManager.MODE_NORMAL);
304        // Abandon audio focus. Gives the previous focus owner, if any, focus.
305        audioManager.abandonAudioFocus(audioFocusChangeListener);
306        audioFocusChangeListener = null;
307        Log.d(Config.LOGTAG, "Abandoned audio focus for VOICE_CALL streams");
308        if (proximitySensor != null) {
309            proximitySensor.stop();
310            proximitySensor = null;
311        }
312        audioManagerEvents = null;
313    }
314
315    /**
316     * Changes selection of the currently active audio device.
317     */
318    private void setAudioDeviceInternal(AudioDevice device) {
319        Log.d(Config.LOGTAG, "setAudioDeviceInternal(device=" + device + ")");
320        AppRTCUtils.assertIsTrue(audioDevices.contains(device));
321        switch (device) {
322            case SPEAKER_PHONE:
323                setSpeakerphoneOn(true);
324                break;
325            case EARPIECE:
326            case WIRED_HEADSET:
327            case BLUETOOTH:
328                setSpeakerphoneOn(false);
329                break;
330            default:
331                Log.e(Config.LOGTAG, "Invalid audio device selection");
332                break;
333        }
334        selectedAudioDevice = device;
335    }
336
337    /**
338     * Changes default audio device.
339     * TODO(henrika): add usage of this method in the AppRTCMobile client.
340     */
341    public void setDefaultAudioDevice(AudioDevice defaultDevice) {
342        ThreadUtils.checkIsOnMainThread();
343        switch (defaultDevice) {
344            case SPEAKER_PHONE:
345                defaultAudioDevice = defaultDevice;
346                break;
347            case EARPIECE:
348                if (hasEarpiece()) {
349                    defaultAudioDevice = defaultDevice;
350                } else {
351                    defaultAudioDevice = AudioDevice.SPEAKER_PHONE;
352                }
353                break;
354            default:
355                Log.e(Config.LOGTAG, "Invalid default audio device selection");
356                break;
357        }
358        Log.d(Config.LOGTAG, "setDefaultAudioDevice(device=" + defaultAudioDevice + ")");
359        updateAudioDeviceState();
360    }
361
362    /**
363     * Changes selection of the currently active audio device.
364     */
365    public void selectAudioDevice(AudioDevice device) {
366        ThreadUtils.checkIsOnMainThread();
367        if (!audioDevices.contains(device)) {
368            Log.e(Config.LOGTAG, "Can not select " + device + " from available " + audioDevices);
369        }
370        userSelectedAudioDevice = device;
371        updateAudioDeviceState();
372    }
373
374    /**
375     * Returns current set of available/selectable audio devices.
376     */
377    public Set<AudioDevice> getAudioDevices() {
378        ThreadUtils.checkIsOnMainThread();
379        return Collections.unmodifiableSet(new HashSet<>(audioDevices));
380    }
381
382    /**
383     * Returns the currently selected audio device.
384     */
385    public AudioDevice getSelectedAudioDevice() {
386        ThreadUtils.checkIsOnMainThread();
387        return selectedAudioDevice;
388    }
389
390    /**
391     * Helper method for receiver registration.
392     */
393    private void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
394        apprtcContext.registerReceiver(receiver, filter);
395    }
396
397    /**
398     * Helper method for unregistration of an existing receiver.
399     */
400    private void unregisterReceiver(BroadcastReceiver receiver) {
401        apprtcContext.unregisterReceiver(receiver);
402    }
403
404    /**
405     * Sets the speaker phone mode.
406     */
407    private void setSpeakerphoneOn(boolean on) {
408        boolean wasOn = audioManager.isSpeakerphoneOn();
409        if (wasOn == on) {
410            return;
411        }
412        audioManager.setSpeakerphoneOn(on);
413    }
414
415    /**
416     * Sets the microphone mute state.
417     */
418    private void setMicrophoneMute(boolean on) {
419        boolean wasMuted = audioManager.isMicrophoneMute();
420        if (wasMuted == on) {
421            return;
422        }
423        audioManager.setMicrophoneMute(on);
424    }
425
426    /**
427     * Gets the current earpiece state.
428     */
429    private boolean hasEarpiece() {
430        return apprtcContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
431    }
432
433    /**
434     * Checks whether a wired headset is connected or not.
435     * This is not a valid indication that audio playback is actually over
436     * the wired headset as audio routing depends on other conditions. We
437     * only use it as an early indicator (during initialization) of an attached
438     * wired headset.
439     */
440    @Deprecated
441    private boolean hasWiredHeadset() {
442        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
443            return audioManager.isWiredHeadsetOn();
444        } else {
445            final AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_ALL);
446            for (AudioDeviceInfo device : devices) {
447                final int type = device.getType();
448                if (type == AudioDeviceInfo.TYPE_WIRED_HEADSET) {
449                    Log.d(Config.LOGTAG, "hasWiredHeadset: found wired headset");
450                    return true;
451                } else if (type == AudioDeviceInfo.TYPE_USB_DEVICE) {
452                    Log.d(Config.LOGTAG, "hasWiredHeadset: found USB audio device");
453                    return true;
454                }
455            }
456            return false;
457        }
458    }
459
460    /**
461     * Updates list of possible audio devices and make new device selection.
462     * TODO(henrika): add unit test to verify all state transitions.
463     */
464    public void updateAudioDeviceState() {
465        ThreadUtils.checkIsOnMainThread();
466        Log.d(Config.LOGTAG, "--- updateAudioDeviceState: "
467                + "wired headset=" + hasWiredHeadset + ", "
468                + "BT state=" + bluetoothManager.getState());
469        Log.d(Config.LOGTAG, "Device status: "
470                + "available=" + audioDevices + ", "
471                + "selected=" + selectedAudioDevice + ", "
472                + "user selected=" + userSelectedAudioDevice);
473        // Check if any Bluetooth headset is connected. The internal BT state will
474        // change accordingly.
475        // TODO(henrika): perhaps wrap required state into BT manager.
476        if (bluetoothManager.getState() == AppRTCBluetoothManager.State.HEADSET_AVAILABLE
477                || bluetoothManager.getState() == AppRTCBluetoothManager.State.HEADSET_UNAVAILABLE
478                || bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_DISCONNECTING) {
479            bluetoothManager.updateDevice();
480        }
481        // Update the set of available audio devices.
482        Set<AudioDevice> newAudioDevices = new HashSet<>();
483        if (bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_CONNECTED
484                || bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_CONNECTING
485                || bluetoothManager.getState() == AppRTCBluetoothManager.State.HEADSET_AVAILABLE) {
486            newAudioDevices.add(AudioDevice.BLUETOOTH);
487        }
488        if (hasWiredHeadset) {
489            // If a wired headset is connected, then it is the only possible option.
490            newAudioDevices.add(AudioDevice.WIRED_HEADSET);
491        } else {
492            // No wired headset, hence the audio-device list can contain speaker
493            // phone (on a tablet), or speaker phone and earpiece (on mobile phone).
494            newAudioDevices.add(AudioDevice.SPEAKER_PHONE);
495            if (hasEarpiece()) {
496                newAudioDevices.add(AudioDevice.EARPIECE);
497            }
498        }
499        // Store state which is set to true if the device list has changed.
500        boolean audioDeviceSetUpdated = !audioDevices.equals(newAudioDevices);
501        // Update the existing audio device set.
502        audioDevices = newAudioDevices;
503        // Correct user selected audio devices if needed.
504        if (bluetoothManager.getState() == AppRTCBluetoothManager.State.HEADSET_UNAVAILABLE
505                && userSelectedAudioDevice == AudioDevice.BLUETOOTH) {
506            // If BT is not available, it can't be the user selection.
507            userSelectedAudioDevice = AudioDevice.NONE;
508        }
509        if (hasWiredHeadset && userSelectedAudioDevice == AudioDevice.SPEAKER_PHONE) {
510            // If user selected speaker phone, but then plugged wired headset then make
511            // wired headset as user selected device.
512            userSelectedAudioDevice = AudioDevice.WIRED_HEADSET;
513        }
514        if (!hasWiredHeadset && userSelectedAudioDevice == AudioDevice.WIRED_HEADSET) {
515            // If user selected wired headset, but then unplugged wired headset then make
516            // speaker phone as user selected device.
517            userSelectedAudioDevice = AudioDevice.SPEAKER_PHONE;
518        }
519        // Need to start Bluetooth if it is available and user either selected it explicitly or
520        // user did not select any output device.
521        boolean needBluetoothAudioStart =
522                bluetoothManager.getState() == AppRTCBluetoothManager.State.HEADSET_AVAILABLE
523                        && (userSelectedAudioDevice == AudioDevice.NONE
524                        || userSelectedAudioDevice == AudioDevice.BLUETOOTH);
525        // Need to stop Bluetooth audio if user selected different device and
526        // Bluetooth SCO connection is established or in the process.
527        boolean needBluetoothAudioStop =
528                (bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_CONNECTED
529                        || bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_CONNECTING)
530                        && (userSelectedAudioDevice != AudioDevice.NONE
531                        && userSelectedAudioDevice != AudioDevice.BLUETOOTH);
532        if (bluetoothManager.getState() == AppRTCBluetoothManager.State.HEADSET_AVAILABLE
533                || bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_CONNECTING
534                || bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_CONNECTED) {
535            Log.d(Config.LOGTAG, "Need BT audio: start=" + needBluetoothAudioStart + ", "
536                    + "stop=" + needBluetoothAudioStop + ", "
537                    + "BT state=" + bluetoothManager.getState());
538        }
539        // Start or stop Bluetooth SCO connection given states set earlier.
540        if (needBluetoothAudioStop) {
541            bluetoothManager.stopScoAudio();
542            bluetoothManager.updateDevice();
543        }
544        if (needBluetoothAudioStart && !needBluetoothAudioStop) {
545            // Attempt to start Bluetooth SCO audio (takes a few second to start).
546            if (!bluetoothManager.startScoAudio()) {
547                // Remove BLUETOOTH from list of available devices since SCO failed.
548                audioDevices.remove(AudioDevice.BLUETOOTH);
549                audioDeviceSetUpdated = true;
550            }
551        }
552        // Update selected audio device.
553        final AudioDevice newAudioDevice;
554        if (bluetoothManager.getState() == AppRTCBluetoothManager.State.SCO_CONNECTED) {
555            // If a Bluetooth is connected, then it should be used as output audio
556            // device. Note that it is not sufficient that a headset is available;
557            // an active SCO channel must also be up and running.
558            newAudioDevice = AudioDevice.BLUETOOTH;
559        } else if (hasWiredHeadset) {
560            // If a wired headset is connected, but Bluetooth is not, then wired headset is used as
561            // audio device.
562            newAudioDevice = AudioDevice.WIRED_HEADSET;
563        } else {
564            // No wired headset and no Bluetooth, hence the audio-device list can contain speaker
565            // phone (on a tablet), or speaker phone and earpiece (on mobile phone).
566            // |defaultAudioDevice| contains either AudioDevice.SPEAKER_PHONE or AudioDevice.EARPIECE
567            // depending on the user's selection.
568            newAudioDevice = defaultAudioDevice;
569        }
570        // Switch to new device but only if there has been any changes.
571        if (newAudioDevice != selectedAudioDevice || audioDeviceSetUpdated) {
572            // Do the required device switch.
573            setAudioDeviceInternal(newAudioDevice);
574            Log.d(Config.LOGTAG, "New device status: "
575                    + "available=" + audioDevices + ", "
576                    + "selected=" + newAudioDevice);
577            if (audioManagerEvents != null) {
578                // Notify a listening client that audio device has been changed.
579                audioManagerEvents.onAudioDeviceChanged(selectedAudioDevice, audioDevices);
580            }
581        }
582        Log.d(Config.LOGTAG, "--- updateAudioDeviceState done");
583    }
584
585    /**
586     * AudioDevice is the names of possible audio devices that we currently
587     * support.
588     */
589    public enum AudioDevice {SPEAKER_PHONE, WIRED_HEADSET, EARPIECE, BLUETOOTH, NONE}
590
591    /**
592     * AudioManager state.
593     */
594    public enum AudioManagerState {
595        UNINITIALIZED,
596        PREINITIALIZED,
597        RUNNING,
598    }
599
600    public enum SpeakerPhonePreference {
601        AUTO, EARPIECE, SPEAKER;
602
603        public static SpeakerPhonePreference of(final Set<Media> media) {
604            if (media.contains(Media.VIDEO)) {
605                return SPEAKER;
606            } else {
607                return EARPIECE;
608            }
609        }
610    }
611
612    /**
613     * Selected audio device change event.
614     */
615    public interface AudioManagerEvents {
616        // Callback fired once audio device is changed or list of available audio devices changed.
617        void onAudioDeviceChanged(
618                AudioDevice selectedAudioDevice, Set<AudioDevice> availableAudioDevices);
619    }
620
621    /* Receiver which handles changes in wired headset availability. */
622    private class WiredHeadsetReceiver extends BroadcastReceiver {
623        private static final int STATE_UNPLUGGED = 0;
624        private static final int STATE_PLUGGED = 1;
625        private static final int HAS_NO_MIC = 0;
626        private static final int HAS_MIC = 1;
627
628        @Override
629        public void onReceive(Context context, Intent intent) {
630            int state = intent.getIntExtra("state", STATE_UNPLUGGED);
631            int microphone = intent.getIntExtra("microphone", HAS_NO_MIC);
632            String name = intent.getStringExtra("name");
633            Log.d(Config.LOGTAG, "WiredHeadsetReceiver.onReceive" + AppRTCUtils.getThreadInfo() + ": "
634                    + "a=" + intent.getAction() + ", s="
635                    + (state == STATE_UNPLUGGED ? "unplugged" : "plugged") + ", m="
636                    + (microphone == HAS_MIC ? "mic" : "no mic") + ", n=" + name + ", sb="
637                    + isInitialStickyBroadcast());
638            hasWiredHeadset = (state == STATE_PLUGGED);
639            updateAudioDeviceState();
640        }
641    }
642}