summaryrefslogtreecommitdiffstats
path: root/src/org/cyanogenmod/audiofx/audiofx/activity/MasterConfigControl.java
blob: d83d0dec70f39557c5142dce6468a701716145fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package com.cyngn.audiofx.activity;

import static android.media.AudioDeviceInfo.TYPE_BLUETOOTH_A2DP;
import static android.media.AudioDeviceInfo.TYPE_BLUETOOTH_SCO;
import static android.media.AudioDeviceInfo.TYPE_DOCK;
import static android.media.AudioDeviceInfo.TYPE_IP;
import static android.media.AudioDeviceInfo.TYPE_LINE_ANALOG;
import static android.media.AudioDeviceInfo.TYPE_LINE_DIGITAL;
import static android.media.AudioDeviceInfo.TYPE_USB_ACCESSORY;
import static android.media.AudioDeviceInfo.TYPE_USB_DEVICE;
import static android.media.AudioDeviceInfo.TYPE_WIRED_HEADPHONES;
import static android.media.AudioDeviceInfo.TYPE_WIRED_HEADSET;
import static android.media.AudioDeviceInfo.convertDeviceTypeToInternalDevice;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.cyngn.audiofx.Constants;
import com.cyngn.audiofx.service.AudioFxService;

import java.util.ArrayList;
import java.util.List;

/**
 * Master configuration class for AudioFX.
 *
 * Contains the main hub where data is stored for the current eq graph (which there should be
 * one of, thus only once instance of this class exists).
 *
 * Anyone can obtain an instance of this class. If one does not exist, a new one is created.
 * Immediately before the new instance creation happens, some defaults are pre-populated
 * with MasterConfigControl.saveDefaults(). That method doesn't ever have to be directly called.
 */
public class MasterConfigControl {

    private static final String TAG = MasterConfigControl.class.getSimpleName();
    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
    private static final boolean SERVICE_DEBUG = false;

    private final Context mContext;

    private AudioFxService.LocalBinder mService;
    private ServiceConnection mServiceConnection;
    private int mServiceRefCount = 0;

    private AudioDeviceInfo mCurrentDevice;
    private AudioDeviceInfo mUserDeviceOverride;

    private final StateCallbacks mCallbacks;
    private final EqualizerManager mEqManager;
    private final AudioManager mAudioManager;

    private static MasterConfigControl sInstance;
    private boolean mShouldBindToService = false;

    public static MasterConfigControl getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new MasterConfigControl(context);
        }
        return sInstance;
    }

    private MasterConfigControl(Context context) {
        mContext = context.getApplicationContext();

        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        mCallbacks = new StateCallbacks(this);
        mEqManager = new EqualizerManager(context, this);
    }

    public void onResetDefaults() {
        mEqManager.applyDefaults();
    }

    public synchronized boolean bindService() {
        boolean conn = true;
        if (SERVICE_DEBUG) Log.i(TAG, "bindService() refCount=" + mServiceRefCount);
        if (mServiceConnection == null && mServiceRefCount == 0) {
            mServiceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder binder) {
                    if (SERVICE_DEBUG) Log.i(TAG, "onServiceConnected refCount=" + mServiceRefCount);
                    mService = ((AudioFxService.LocalBinder) binder);
                    LocalBroadcastManager.getInstance(mContext).registerReceiver(
                            mDeviceChangeReceiver,
                            new IntentFilter(AudioFxService.ACTION_DEVICE_OUTPUT_CHANGED));
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {
                    if (SERVICE_DEBUG) Log.w(TAG, "onServiceDisconnected refCount =" + mServiceRefCount);
                    LocalBroadcastManager.getInstance(mContext).unregisterReceiver(
                            mDeviceChangeReceiver);
                    mService = null;
                }
            };

            Intent serviceIntent = new Intent(mContext, AudioFxService.class);
            conn =  mContext.bindService(serviceIntent, mServiceConnection,
                    Context.BIND_AUTO_CREATE);
        }
        if (conn) {
            mServiceRefCount++;
        }
        return mServiceRefCount > 0;
    }

    public synchronized void unbindService() {
        if (SERVICE_DEBUG) Log.i(TAG, "unbindService() called refCount=" + mServiceRefCount);
        if (mServiceRefCount > 0) {
            mServiceRefCount--;
            if (mServiceRefCount == 0) {
                mContext.unbindService(mServiceConnection);
                mService = null;
                mServiceConnection = null;
            }
        }
    }

    public boolean checkService() {
        if (mService == null && mServiceRefCount == 0 && mShouldBindToService) {
            Log.e(TAG,  "Service went away, rebinding");
            bindService();
        }
        return mService != null;
    }

    private final BroadcastReceiver mDeviceChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int device = intent.getIntExtra("device", -1);
            Log.d(TAG, "deviceChanged: " + device);
            if (device > -1) {
                AudioDeviceInfo info = getDeviceById(device);
                if (info != null) {
                    setCurrentDevice(info, false);
                }
            }
        }
    };

    public void updateService(int flags) {
        if (checkService()) {
            mService.update(flags);
        }
    }

    public StateCallbacks getCallbacks() {
        return mCallbacks;
    }

    public EqualizerManager getEqualizerManager() {
        return mEqManager;
    }

    public synchronized void setCurrentDeviceEnabled(boolean isChecked) {
        getPrefs().edit().putBoolean(Constants.DEVICE_AUDIOFX_GLOBAL_ENABLE, isChecked).apply();
        getCallbacks().notifyGlobalToggle(isChecked);
        updateService(AudioFxService.ALL_CHANGED);
    }

    public synchronized boolean isCurrentDeviceEnabled() {
        return getPrefs().getBoolean(Constants.DEVICE_AUDIOFX_GLOBAL_ENABLE, false);
    }

    public synchronized SharedPreferences getGlobalPrefs() {
        return mContext.getSharedPreferences(Constants.AUDIOFX_GLOBAL_FILE, 0);
    }

    /**
     * Update the current device used when querying any device-specific values such as the current
     * preset, or the user's custom eq preset settings.
     *
     * @param audioOutputRouting the new device key
     */
    public synchronized void setCurrentDevice(AudioDeviceInfo device, final boolean userSwitch) {

        final AudioDeviceInfo current = getCurrentDevice();

        Log.d(TAG, "setCurrentDevice name=" + (current == null ? null : current.getProductName()) +
                " fromUser=" + userSwitch +
                " cur=" + (current == null ? null : current.getType()) +
                " new=" + (device == null ? null : device.getType()));

        if (userSwitch) {
            mUserDeviceOverride = device;
        } else {
            if (device != null) {
                mCurrentDevice = device;
            }
            mUserDeviceOverride = null;
        }

        mEqManager.onPreDeviceChanged();

        mCallbacks.notifyDeviceChanged(device, userSwitch);

        mEqManager.onPostDeviceChanged();
    }

    public AudioDeviceInfo getSystemDevice() {
        if (mCurrentDevice == null) {
            final int forMusic = mAudioManager.getDevicesForStream(AudioManager.STREAM_MUSIC);
            for (AudioDeviceInfo ai : getConnectedDevices()) {
                if ((convertDeviceTypeToInternalDevice(ai.getType()) & forMusic) > 0) {
                    return ai;
                }
            }
        }
        return mCurrentDevice;
    }

    public boolean isUserDeviceOverride() {
        return mUserDeviceOverride != null;
    }

    public AudioDeviceInfo getCurrentDevice() {
        if (isUserDeviceOverride()) {
            return mUserDeviceOverride;
        }
        return getSystemDevice();
    }

    public AudioDeviceInfo getDeviceById(int id) {
        for (AudioDeviceInfo ai : mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
            if (ai.getId() == id) {
                return ai;
            }
        }
        return null;
    }

    public List<AudioDeviceInfo> getConnectedDevices(int... filter) {
        final List<AudioDeviceInfo> devices = new ArrayList<AudioDeviceInfo>();
        for (AudioDeviceInfo ai : mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
            if (filter.length == 0) {
                devices.add(ai);
            } else {
                for (int i = 0; i < filter.length; i++) {
                    if (ai.getType() == filter[i]) {
                        devices.add(ai);
                        continue;
                    }
                }
            }
        }
        return devices;
    }

    public String getCurrentDeviceIdentifier() {
        return getDeviceIdentifierString(getCurrentDevice());
    }

    public SharedPreferences getPrefs() {
        return mContext.getSharedPreferences(getCurrentDeviceIdentifier(), 0);
    }

    public boolean hasDts() {
        return getGlobalPrefs().getBoolean(Constants.AUDIOFX_GLOBAL_HAS_DTS, false);
    }

    public boolean hasMaxxAudio() {
        return getGlobalPrefs().getBoolean(Constants.AUDIOFX_GLOBAL_HAS_MAXXAUDIO, false);
    }

    public boolean getMaxxVolumeEnabled() {
        return getPrefs().getBoolean(Constants.DEVICE_AUDIOFX_MAXXVOLUME_ENABLE, false);
    }

    public boolean hasBassBoost() {
        return getGlobalPrefs().getBoolean(Constants.AUDIOFX_GLOBAL_HAS_BASSBOOST, false);
    }

    public boolean hasVirtualizer() {
        return getGlobalPrefs().getBoolean(Constants.AUDIOFX_GLOBAL_HAS_VIRTUALIZER, false);
    }

    public void setMaxxVolumeEnabled(boolean enable) {
        getPrefs().edit().putBoolean(Constants.DEVICE_AUDIOFX_MAXXVOLUME_ENABLE, enable).apply();
        updateService(AudioFxService.VOLUME_BOOST_CHANGED);
    }

    void overrideEqLevels(short band, short level) {
        if (checkService()) {
            mService.setOverrideLevels(band, level);
        }
    }

    public static String getDeviceDisplayString(Context context,  AudioDeviceInfo info) {
        int type = info == null ? -1 : info.getType();
        switch (type) {
            case TYPE_WIRED_HEADSET:
            case TYPE_WIRED_HEADPHONES:
                return context.getString(com.cyngn.audiofx.R.string.device_headset);
            case TYPE_LINE_ANALOG:
            case TYPE_LINE_DIGITAL:
                return context.getString(com.cyngn.audiofx.R.string.device_line_out);
            case TYPE_BLUETOOTH_SCO:
            case TYPE_BLUETOOTH_A2DP:
            case TYPE_USB_DEVICE:
            case TYPE_USB_ACCESSORY:
            case TYPE_DOCK:
            case TYPE_IP:
                return info.getProductName().toString();
            default:
                return context.getString(com.cyngn.audiofx.R.string.device_speaker);
        }
    }

    private static String appendProductName(AudioDeviceInfo info, String prefix) {
        StringBuilder nm = new StringBuilder(prefix);
        if (info != null && info.getProductName() != null) {
            nm.append("-").append(info.getProductName().toString().replaceAll("\\W+", ""));
        }
        return nm.toString();
    }

    private static String appendDeviceAddress(AudioDeviceInfo info, String prefix) {
        StringBuilder nm = new StringBuilder(prefix);
        if (info != null && info.getAddress() != null) {
            nm.append("-").append(info.getAddress().replace(":", ""));
        }
        return nm.toString();
    }

    public static String getDeviceIdentifierString(AudioDeviceInfo info) {
        int type = info == null ? -1 : info.getType();
        switch (type) {
            case TYPE_WIRED_HEADSET:
            case TYPE_WIRED_HEADPHONES:
                return Constants.DEVICE_HEADSET;
            case TYPE_LINE_ANALOG:
            case TYPE_LINE_DIGITAL:
                return Constants.DEVICE_LINE_OUT;
            case TYPE_BLUETOOTH_SCO:
            case TYPE_BLUETOOTH_A2DP:
                return appendDeviceAddress(info, Constants.DEVICE_PREFIX_BLUETOOTH);
            case TYPE_USB_DEVICE:
            case TYPE_USB_ACCESSORY:
            case TYPE_DOCK:
                return appendProductName(info, Constants.DEVICE_PREFIX_USB);
            case TYPE_IP:
                return appendProductName(info, Constants.DEVICE_PREFIX_CAST);
            default:
                return Constants.DEVICE_SPEAKER;
        }
    }

    /**
     * Set whether to automatically attempt to bind to the service.
     * @param bindToService
     */
    public void setAutoBindToService(boolean bindToService) {
        mShouldBindToService = bindToService;
    }
}