summaryrefslogtreecommitdiffstats
path: root/src/org/cyanogenmod/audiofx/audiofx/service/DevicePreferenceManager.java
blob: 928209e95a4ebcf20680711550bcaf353fc8a667 (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
package com.cyngn.audiofx.service;

import static com.cyngn.audiofx.Constants.AUDIOFX_GLOBAL_FILE;
import static com.cyngn.audiofx.Constants.AUDIOFX_GLOBAL_HAS_BASSBOOST;
import static com.cyngn.audiofx.Constants.AUDIOFX_GLOBAL_HAS_DTS;
import static com.cyngn.audiofx.Constants.AUDIOFX_GLOBAL_HAS_MAXXAUDIO;
import static com.cyngn.audiofx.Constants.AUDIOFX_GLOBAL_HAS_VIRTUALIZER;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_BASS_ENABLE;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_BASS_STRENGTH;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_EQ_PRESET;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_GLOBAL_ENABLE;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_MAXXVOLUME_ENABLE;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_TREBLE_ENABLE;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_TREBLE_STRENGTH;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_VIRTUALIZER_ENABLE;
import static com.cyngn.audiofx.Constants.DEVICE_AUDIOFX_VIRTUALIZER_STRENGTH;
import static com.cyngn.audiofx.Constants.DEVICE_HEADSET;
import static com.cyngn.audiofx.Constants.DEVICE_SPEAKER;
import static com.cyngn.audiofx.Constants.EQUALIZER_BAND_LEVEL_RANGE;
import static com.cyngn.audiofx.Constants.EQUALIZER_CENTER_FREQS;
import static com.cyngn.audiofx.Constants.EQUALIZER_NUMBER_OF_BANDS;
import static com.cyngn.audiofx.Constants.EQUALIZER_NUMBER_OF_PRESETS;
import static com.cyngn.audiofx.Constants.EQUALIZER_PRESET;
import static com.cyngn.audiofx.Constants.EQUALIZER_PRESET_NAMES;
import static com.cyngn.audiofx.Constants.SAVED_DEFAULTS;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.AudioDeviceInfo;
import android.text.TextUtils;
import android.util.Log;

import com.cyngn.audiofx.Constants;
import com.cyngn.audiofx.R;
import com.cyngn.audiofx.activity.MasterConfigControl;
import com.cyngn.audiofx.backends.EffectSet;
import com.cyngn.audiofx.backends.EffectsFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

class DevicePreferenceManager implements AudioOutputChangeListener.AudioOutputChangedCallback {

    private static final String TAG = AudioFxService.TAG;
    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);

    private final Context mContext;

    private AudioDeviceInfo mCurrentDevice;

    public DevicePreferenceManager(Context context, AudioDeviceInfo device) {
        mContext = context;
        mCurrentDevice = device;
    }

    public boolean initDefaults() {
        try {
            saveAndApplyDefaults(false);
        } catch (Exception e) {
            SharedPreferences prefs = Constants.getGlobalPrefs(mContext);
            prefs.edit().clear().commit();
            Log.e(TAG, "Failed to initialize defaults!", e);
            return false;
        }
        return true;
    }

    @Override
    public void onAudioOutputChanged(boolean firstChange, AudioDeviceInfo outputDevice) {
        mCurrentDevice = outputDevice;
    }

    public SharedPreferences getCurrentDevicePrefs() {
        return mContext.getSharedPreferences(
                MasterConfigControl.getDeviceIdentifierString(mCurrentDevice), 0);
    }

    public SharedPreferences prefsFor(final String name) {
        return mContext.getSharedPreferences(name, 0);
    }

    private boolean hasPrefs(final String name) {
        return mContext.getSharedPrefsFile(name).exists();
    }

    public boolean isGlobalEnabled() {
        return getCurrentDevicePrefs().getBoolean(DEVICE_AUDIOFX_GLOBAL_ENABLE, false);
    }

    /**
     * This method sets some sane defaults for presets, device defaults, etc
     * <p/>
     * First we read presets from the system, then adjusts some setting values
     * for some better defaults!
     */
    private void saveAndApplyDefaults(boolean overridePrevious) {
        if (DEBUG) {
            Log.d(TAG, "saveAndApplyDefaults() called with overridePrevious = " +
                    "[" + overridePrevious + "]");
        }
        SharedPreferences prefs = Constants.getGlobalPrefs(mContext);

        final int currentPrefVer = prefs.getInt(Constants.AUDIOFX_GLOBAL_PREFS_VERSION_INT, 0);
        boolean needsPrefsUpdate = currentPrefVer < Constants.CURRENT_PREFS_INT_VERSION
                || overridePrevious;

        if (needsPrefsUpdate) {
            Log.d(TAG, "rebuilding presets due to preference upgrade from " + currentPrefVer
                    + " to " + Constants.CURRENT_PREFS_INT_VERSION);
        }

        if (prefs.getBoolean(SAVED_DEFAULTS, false) && !needsPrefsUpdate) {
            if (DEBUG) {
                Log.e(TAG, "we've already saved defaults and don't need a pref update. aborting.");
            }
            return;
        }
        EffectSet temp = new EffectsFactory().createEffectSet(mContext, 0, null);

        final int numBands = temp.getNumEqualizerBands();
        final int numPresets = temp.getNumEqualizerPresets();
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(EQUALIZER_NUMBER_OF_PRESETS, String.valueOf(numPresets));
        editor.putString(EQUALIZER_NUMBER_OF_BANDS, String.valueOf(numBands));

        // range
        short[] rangeShortArr = temp.getEqualizerBandLevelRange();
        editor.putString(EQUALIZER_BAND_LEVEL_RANGE, rangeShortArr[0]
                + ";" + rangeShortArr[1]);

        // center freqs
        StringBuilder centerFreqs = new StringBuilder();
        // audiofx.global.centerfreqs
        for (short i = 0; i < numBands; i++) {
            centerFreqs.append(temp.getCenterFrequency(i));
            centerFreqs.append(";");

        }
        centerFreqs.deleteCharAt(centerFreqs.length() - 1);
        editor.putString(EQUALIZER_CENTER_FREQS, centerFreqs.toString());

        // populate preset names
        StringBuilder presetNames = new StringBuilder();
        for (int i = 0; i < numPresets; i++) {
            String presetName = temp.getEqualizerPresetName((short) i);
            presetNames.append(presetName);
            presetNames.append("|");

            // populate preset band values
            StringBuilder presetBands = new StringBuilder();
            temp.useEqualizerPreset((short) i);

            for (int j = 0; j < numBands; j++) {
                // loop through preset bands
                presetBands.append(temp.getEqualizerBandLevel((short) j));
                presetBands.append(";");
            }
            presetBands.deleteCharAt(presetBands.length() - 1);
            editor.putString(EQUALIZER_PRESET + i, presetBands.toString());
        }
        if (presetNames.length() > 0) {
            presetNames.deleteCharAt(presetNames.length() - 1);
        }
        editor.putString(EQUALIZER_PRESET_NAMES, presetNames.toString());

        editor.putBoolean(AUDIOFX_GLOBAL_HAS_VIRTUALIZER, temp.hasVirtualizer());
        editor.putBoolean(AUDIOFX_GLOBAL_HAS_BASSBOOST, temp.hasBassBoost());
        editor.putBoolean(AUDIOFX_GLOBAL_HAS_MAXXAUDIO, temp.getBrand() == Constants.EFFECT_TYPE_MAXXAUDIO);
        editor.putBoolean(AUDIOFX_GLOBAL_HAS_DTS, temp.getBrand() == Constants.EFFECT_TYPE_DTS);
        editor.commit();
        temp.release();

        applyDefaults(needsPrefsUpdate);

        prefs
                .edit()
                .putInt(Constants.AUDIOFX_GLOBAL_PREFS_VERSION_INT,
                            Constants.CURRENT_PREFS_INT_VERSION)
                .putBoolean(Constants.SAVED_DEFAULTS, true)
                .commit();
    }

    private static int findInList(String needle, List<String> haystack) {
        for (int i = 0; i < haystack.size(); i++) {
            if (haystack.get(i).equalsIgnoreCase(needle)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * This method sets up some *persisted* defaults.
     * Prereq: saveDefaults() must have been run before this can apply its defaults properly.
     */
    private void applyDefaults(boolean overridePrevious) {
        if (DEBUG) {
            Log.d(TAG, "applyDefaults() called with overridePrevious = [" + overridePrevious + "]");
        }

        if (!(overridePrevious || !hasPrefs(DEVICE_SPEAKER) ||
                !hasPrefs(AUDIOFX_GLOBAL_FILE))) {
            return;
        }

        final SharedPreferences globalPrefs = Constants.getGlobalPrefs(mContext);

        // Nothing to see here for EFFECT_TYPE_DTS
        if (globalPrefs.getBoolean(AUDIOFX_GLOBAL_HAS_DTS, false)) {
            return;
        }

        // set up the builtin speaker configuration
        final String smallSpeakers = getNonLocalizedString(R.string.small_speakers);
        final List<String> presetNames = new ArrayList<String>(Arrays.asList(
                globalPrefs.getString(EQUALIZER_PRESET_NAMES, "").split("\\|")));
        final SharedPreferences speakerPrefs = prefsFor(DEVICE_SPEAKER);

        if (globalPrefs.getBoolean(AUDIOFX_GLOBAL_HAS_MAXXAUDIO, false)) {
            // MaxxAudio defaults for builtin speaker:
            // maxxvolume: on  maxxbass: 40%  maxxtreble: 32%
            speakerPrefs.edit()
                    .putBoolean(DEVICE_AUDIOFX_GLOBAL_ENABLE, true)
                    .putBoolean(DEVICE_AUDIOFX_MAXXVOLUME_ENABLE, true)
                    .putBoolean(DEVICE_AUDIOFX_BASS_ENABLE, true)
                    .putString(DEVICE_AUDIOFX_BASS_STRENGTH, "400")
                    .putBoolean(DEVICE_AUDIOFX_TREBLE_ENABLE, true)
                    .putString(DEVICE_AUDIOFX_TREBLE_STRENGTH, "32")
                    .commit();

            // Defaults for headphones
            // maxxvolume: on  maxxbass: 20%  maxxtreble: 40%  maxxspace: 20%
            prefsFor(DEVICE_HEADSET).edit()
                    .putBoolean(DEVICE_AUDIOFX_GLOBAL_ENABLE, true)
                    .putBoolean(DEVICE_AUDIOFX_MAXXVOLUME_ENABLE, true)
                    .putBoolean(DEVICE_AUDIOFX_BASS_ENABLE, true)
                    .putString(DEVICE_AUDIOFX_BASS_STRENGTH, "200")
                    .putBoolean(DEVICE_AUDIOFX_TREBLE_ENABLE, true)
                    .putString(DEVICE_AUDIOFX_TREBLE_STRENGTH, "40")
                    .putBoolean(DEVICE_AUDIOFX_VIRTUALIZER_ENABLE, true)
                    .putString(DEVICE_AUDIOFX_VIRTUALIZER_STRENGTH, "200")
                    .commit();
        } else {
            // Defaults for headphones
            // bass boost: 15%  virtualizer: 20%  preset: FLAT
            int flat = findInList(getNonLocalizedString(R.string.flat), presetNames);
            prefsFor(DEVICE_HEADSET).edit()
                    .putBoolean(DEVICE_AUDIOFX_GLOBAL_ENABLE, true)
                    .putBoolean(DEVICE_AUDIOFX_BASS_ENABLE, true)
                    .putString(DEVICE_AUDIOFX_BASS_STRENGTH, "150")
                    .putBoolean(DEVICE_AUDIOFX_VIRTUALIZER_ENABLE, true)
                    .putString(DEVICE_AUDIOFX_VIRTUALIZER_STRENGTH, "200")
                    .putString(DEVICE_AUDIOFX_EQ_PRESET, (flat >= 0 ? String.valueOf(flat) : "0"))
                    .commit();
        }

        // for 5 band configs, let's add a `Small Speaker` configuration if one
        // doesn't exist ( from oss AudioFX: -170;270;50;-220;200 )
        if (Integer.parseInt(globalPrefs.getString(EQUALIZER_NUMBER_OF_BANDS, "0")) == 5 &&
                findInList(smallSpeakers, presetNames) < 0) {

            int currentPresets = Integer.parseInt(
                    globalPrefs.getString(EQUALIZER_NUMBER_OF_PRESETS, "0"));

            presetNames.add(smallSpeakers);
            String newPresetNames = TextUtils.join("|", presetNames);
            globalPrefs.edit()
                    .putString(EQUALIZER_PRESET + currentPresets, "-170;270;50;-220;200")
                    .putString(EQUALIZER_PRESET_NAMES, newPresetNames)
                    .putString(EQUALIZER_NUMBER_OF_PRESETS, Integer.toString(++currentPresets))
                    .commit();

        }

        // set the small speakers preset as the default
        int idx = findInList(smallSpeakers, presetNames);
        if (idx >= 0) {
            speakerPrefs.edit()
                .putBoolean(DEVICE_AUDIOFX_GLOBAL_ENABLE, true)
                .putString(DEVICE_AUDIOFX_EQ_PRESET, String.valueOf(idx))
                .commit();
        }
    }

    private String getNonLocalizedString(int res) {
        Configuration config = new Configuration(mContext.getResources().getConfiguration());
        config.setLocale(Locale.ROOT);
        return mContext.createConfigurationContext(config).getString(res);
    }
}