summaryrefslogtreecommitdiffstats
path: root/core/java/android/webkit/HTML5Audio.java
blob: fc5df2d5f59cbbcad7b0dbc6895428df2cf9169f (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
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.webkit;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * HTML5 support class for Audio.
 *
 * This class runs almost entirely on the WebCore thread. The exception is when
 * accessing the WebView object to determine whether private browsing is
 * enabled.
 */
class HTML5Audio extends Handler
                 implements MediaPlayer.OnBufferingUpdateListener,
                            MediaPlayer.OnCompletionListener,
                            MediaPlayer.OnErrorListener,
                            MediaPlayer.OnPreparedListener,
                            MediaPlayer.OnSeekCompleteListener,
                            AudioManager.OnAudioFocusChangeListener {
    // Logging tag.
    private static final String LOGTAG = "HTML5Audio";

    private MediaPlayer mMediaPlayer;

    // The C++ MediaPlayerPrivateAndroid object.
    private int mNativePointer;
    // The private status of the view that created this player
    private IsPrivateBrowsingEnabledGetter mIsPrivateBrowsingEnabledGetter;

    private static int IDLE        =  0;
    private static int INITIALIZED =  1;
    private static int PREPARED    =  2;
    private static int STARTED     =  4;
    private static int COMPLETE    =  5;
    private static int PAUSED      =  6;
    private static int STOPPED     = -2;
    private static int ERROR       = -1;

    private int mState = IDLE;

    private String mUrl;
    private boolean mAskToPlay = false;
    private boolean mLoopEnabled = false;
    private boolean mProcessingOnEnd = false;
    private Context mContext;

    // Timer thread -> UI thread
    private static final int TIMEUPDATE = 100;

    private static final String COOKIE = "Cookie";
    private static final String HIDE_URL_LOGS = "x-hide-urls-from-log";

    // The spec says the timer should fire every 250 ms or less.
    private static final int TIMEUPDATE_PERIOD = 250;  // ms
    // The timer for timeupate events.
    // See http://www.whatwg.org/specs/web-apps/current-work/#event-media-timeupdate
    private Timer mTimer;
    private final class TimeupdateTask extends TimerTask {
        public void run() {
            HTML5Audio.this.obtainMessage(TIMEUPDATE).sendToTarget();
        }
    }

    // Helper class to determine whether private browsing is enabled in the
    // given WebView. Queries the WebView on the UI thread. Calls to get()
    // block until the data is available.
    private class IsPrivateBrowsingEnabledGetter {
        private boolean mIsReady;
        private boolean mIsPrivateBrowsingEnabled;
        IsPrivateBrowsingEnabledGetter(Looper uiThreadLooper, final WebViewClassic webView) {
            new Handler(uiThreadLooper).post(new Runnable() {
                @Override
                public void run() {
                    synchronized(IsPrivateBrowsingEnabledGetter.this) {
                        mIsPrivateBrowsingEnabled = webView.isPrivateBrowsingEnabled();
                        mIsReady = true;
                        IsPrivateBrowsingEnabledGetter.this.notify();
                    }
                }
            });
        }
        synchronized boolean get() {
            while (!mIsReady) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
            return mIsPrivateBrowsingEnabled;
        }
    };

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case TIMEUPDATE: {
                try {
                    if (mState != ERROR && mMediaPlayer.isPlaying()) {
                        int position = mMediaPlayer.getCurrentPosition();
                        nativeOnTimeupdate(position, mNativePointer);
                    }
                } catch (IllegalStateException e) {
                    mState = ERROR;
                }
            }
        }
    }

    // event listeners for MediaPlayer
    // Those are called from the same thread we created the MediaPlayer
    // (i.e. the webviewcore thread here)

    // MediaPlayer.OnBufferingUpdateListener
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        nativeOnBuffering(percent, mNativePointer);
    }

    // MediaPlayer.OnCompletionListener;
    public void onCompletion(MediaPlayer mp) {
        mState = COMPLETE;
        mProcessingOnEnd = true;
        nativeOnEnded(mNativePointer);
        mProcessingOnEnd = false;
        if (mLoopEnabled == true) {
            nativeOnRequestPlay(mNativePointer);
            mLoopEnabled = false;
        }
    }

    // MediaPlayer.OnErrorListener
    public boolean onError(MediaPlayer mp, int what, int extra) {
        mState = ERROR;
        resetMediaPlayer();
        mState = IDLE;
        return false;
    }

    // MediaPlayer.OnPreparedListener
    public void onPrepared(MediaPlayer mp) {
        mState = PREPARED;
        if (mTimer != null) {
            mTimer.schedule(new TimeupdateTask(),
                            TIMEUPDATE_PERIOD, TIMEUPDATE_PERIOD);
        }
        nativeOnPrepared(mp.getDuration(), 0, 0, mNativePointer);
        if (mAskToPlay) {
            mAskToPlay = false;
            play();
        }
    }

    // MediaPlayer.OnSeekCompleteListener
    public void onSeekComplete(MediaPlayer mp) {
        nativeOnTimeupdate(mp.getCurrentPosition(), mNativePointer);
    }


    /**
     * @param nativePtr is the C++ pointer to the MediaPlayerPrivate object.
     */
    public HTML5Audio(WebViewCore webViewCore, int nativePtr) {
        // Save the native ptr
        mNativePointer = nativePtr;
        resetMediaPlayer();
        mContext = webViewCore.getContext();
        mIsPrivateBrowsingEnabledGetter = new IsPrivateBrowsingEnabledGetter(
                webViewCore.getContext().getMainLooper(), webViewCore.getWebViewClassic());
    }

    private void resetMediaPlayer() {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        } else {
            mMediaPlayer.reset();
        }
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);

        if (mTimer != null) {
            mTimer.cancel();
        }
        mTimer = new Timer();
        mState = IDLE;
    }

    private void setDataSource(String url) {
        mUrl = url;
        try {
            if (mState != IDLE) {
                resetMediaPlayer();
            }
            String cookieValue = CookieManager.getInstance().getCookie(
                    url, mIsPrivateBrowsingEnabledGetter.get());
            Map<String, String> headers = new HashMap<String, String>();

            if (cookieValue != null) {
                headers.put(COOKIE, cookieValue);
            }
            if (mIsPrivateBrowsingEnabledGetter.get()) {
                headers.put(HIDE_URL_LOGS, "true");
            }

            mMediaPlayer.setDataSource(url, headers);
            mState = INITIALIZED;
            mMediaPlayer.prepareAsync();
        } catch (IOException e) {
            String debugUrl = url.length() > 128 ? url.substring(0, 128) + "..." : url;
            Log.e(LOGTAG, "couldn't load the resource: "+ debugUrl +" exc: " + e);
            resetMediaPlayer();
        }
    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            // resume playback
            if (mMediaPlayer == null) {
                resetMediaPlayer();
            } else if (mState != ERROR && !mMediaPlayer.isPlaying()) {
                mMediaPlayer.start();
                mState = STARTED;
            }
            break;

        case AudioManager.AUDIOFOCUS_LOSS:
            // Lost focus for an unbounded amount of time: stop playback.
            if (mState != ERROR && mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mState = STOPPED;
            }
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // Lost focus for a short time, but we have to stop
            // playback.
            if (mState != ERROR && mMediaPlayer.isPlaying()) pause();
            break;
        }
    }


    private void play() {
        if (mState == COMPLETE && mLoopEnabled == true) {
            // Play it again, Sam
            mMediaPlayer.start();
            mState = STARTED;
            return;
        }

        if (((mState >= ERROR && mState < PREPARED)) && mUrl != null) {
            resetMediaPlayer();
            setDataSource(mUrl);
            mAskToPlay = true;
        }

        if (mState >= PREPARED) {
            AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                mMediaPlayer.start();
                mState = STARTED;
            }
        }
    }

    private void pause() {
        if (mState == STARTED) {
            if (mTimer != null) {
                mTimer.purge();
            }
            mMediaPlayer.pause();
            mState = PAUSED;
        }
    }

    private void seek(int msec) {
        if (mProcessingOnEnd == true && mState == COMPLETE && msec == 0) {
            mLoopEnabled = true;
        }
        if (mState >= PREPARED) {
            mMediaPlayer.seekTo(msec);
        }
    }

    /**
     * Called only over JNI when WebKit is happy to
     * destroy the media player.
     */
    private void teardown() {
        mMediaPlayer.release();
        mMediaPlayer = null;
        mState = ERROR;
        mNativePointer = 0;
    }

    private float getMaxTimeSeekable() {
        if (mState >= PREPARED) {
            return mMediaPlayer.getDuration() / 1000.0f;
        } else {
            return 0;
        }
    }

    private native void nativeOnBuffering(int percent, int nativePointer);
    private native void nativeOnEnded(int nativePointer);
    private native void nativeOnRequestPlay(int nativePointer);
    private native void nativeOnPrepared(int duration, int width, int height, int nativePointer);
    private native void nativeOnTimeupdate(int position, int nativePointer);

}