MediaPlayer.java revision 83ddaf664c7a9eb2759269ec75d25dba48edebf2
1/*
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
17package android.media;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.res.AssetFileDescriptor;
25import android.net.Proxy;
26import android.net.ProxyProperties;
27import android.net.Uri;
28import android.os.Handler;
29import android.os.Looper;
30import android.os.Message;
31import android.os.Parcel;
32import android.os.Parcelable;
33import android.os.ParcelFileDescriptor;
34import android.os.PowerManager;
35import android.util.Log;
36import android.view.Surface;
37import android.view.SurfaceHolder;
38import android.graphics.Bitmap;
39import android.graphics.SurfaceTexture;
40import android.media.AudioManager;
41import android.media.MediaFormat;
42import android.media.SubtitleData;
43
44import java.io.File;
45import java.io.FileDescriptor;
46import java.io.FileInputStream;
47import java.io.IOException;
48import java.net.InetSocketAddress;
49import java.util.Map;
50import java.util.Set;
51import java.lang.ref.WeakReference;
52
53/**
54 * MediaPlayer class can be used to control playback
55 * of audio/video files and streams. An example on how to use the methods in
56 * this class can be found in {@link android.widget.VideoView}.
57 *
58 * <p>Topics covered here are:
59 * <ol>
60 * <li><a href="#StateDiagram">State Diagram</a>
61 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
62 * <li><a href="#Permissions">Permissions</a>
63 * <li><a href="#Callbacks">Register informational and error callbacks</a>
64 * </ol>
65 *
66 * <div class="special reference">
67 * <h3>Developer Guides</h3>
68 * <p>For more information about how to use MediaPlayer, read the
69 * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
70 * </div>
71 *
72 * <a name="StateDiagram"></a>
73 * <h3>State Diagram</h3>
74 *
75 * <p>Playback control of audio/video files and streams is managed as a state
76 * machine. The following diagram shows the life cycle and the states of a
77 * MediaPlayer object driven by the supported playback control operations.
78 * The ovals represent the states a MediaPlayer object may reside
79 * in. The arcs represent the playback control operations that drive the object
80 * state transition. There are two types of arcs. The arcs with a single arrow
81 * head represent synchronous method calls, while those with
82 * a double arrow head represent asynchronous method calls.</p>
83 *
84 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
85 *         alt="MediaPlayer State diagram"
86 *         border="0" /></p>
87 *
88 * <p>From this state diagram, one can see that a MediaPlayer object has the
89 *    following states:</p>
90 * <ul>
91 *     <li>When a MediaPlayer object is just created using <code>new</code> or
92 *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
93 *         {@link #release()} is called, it is in the <em>End</em> state. Between these
94 *         two states is the life cycle of the MediaPlayer object.
95 *         <ul>
96 *         <li>There is a subtle but important difference between a newly constructed
97 *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
98 *         is called. It is a programming error to invoke methods such
99 *         as {@link #getCurrentPosition()},
100 *         {@link #getDuration()}, {@link #getVideoHeight()},
101 *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
102 *         {@link #setLooping(boolean)},
103 *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
104 *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
105 *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
106 *         methods is called right after a MediaPlayer object is constructed,
107 *         the user supplied callback method OnErrorListener.onError() won't be
108 *         called by the internal player engine and the object state remains
109 *         unchanged; but if these methods are called right after {@link #reset()},
110 *         the user supplied callback method OnErrorListener.onError() will be
111 *         invoked by the internal player engine and the object will be
112 *         transfered to the <em>Error</em> state. </li>
113 *         <li>It is also recommended that once
114 *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
115 *         so that resources used by the internal player engine associated with the
116 *         MediaPlayer object can be released immediately. Resource may include
117 *         singleton resources such as hardware acceleration components and
118 *         failure to call {@link #release()} may cause subsequent instances of
119 *         MediaPlayer objects to fallback to software implementations or fail
120 *         altogether. Once the MediaPlayer
121 *         object is in the <em>End</em> state, it can no longer be used and
122 *         there is no way to bring it back to any other state. </li>
123 *         <li>Furthermore,
124 *         the MediaPlayer objects created using <code>new</code> is in the
125 *         <em>Idle</em> state, while those created with one
126 *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
127 *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
128 *         state if the creation using <code>create</code> method is successful.
129 *         </li>
130 *         </ul>
131 *         </li>
132 *     <li>In general, some playback control operation may fail due to various
133 *         reasons, such as unsupported audio/video format, poorly interleaved
134 *         audio/video, resolution too high, streaming timeout, and the like.
135 *         Thus, error reporting and recovery is an important concern under
136 *         these circumstances. Sometimes, due to programming errors, invoking a playback
137 *         control operation in an invalid state may also occur. Under all these
138 *         error conditions, the internal player engine invokes a user supplied
139 *         OnErrorListener.onError() method if an OnErrorListener has been
140 *         registered beforehand via
141 *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
142 *         <ul>
143 *         <li>It is important to note that once an error occurs, the
144 *         MediaPlayer object enters the <em>Error</em> state (except as noted
145 *         above), even if an error listener has not been registered by the application.</li>
146 *         <li>In order to reuse a MediaPlayer object that is in the <em>
147 *         Error</em> state and recover from the error,
148 *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
149 *         state.</li>
150 *         <li>It is good programming practice to have your application
151 *         register a OnErrorListener to look out for error notifications from
152 *         the internal player engine.</li>
153 *         <li>IllegalStateException is
154 *         thrown to prevent programming errors such as calling {@link #prepare()},
155 *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
156 *         </code> methods in an invalid state. </li>
157 *         </ul>
158 *         </li>
159 *     <li>Calling
160 *         {@link #setDataSource(FileDescriptor)}, or
161 *         {@link #setDataSource(String)}, or
162 *         {@link #setDataSource(Context, Uri)}, or
163 *         {@link #setDataSource(FileDescriptor, long, long)} transfers a
164 *         MediaPlayer object in the <em>Idle</em> state to the
165 *         <em>Initialized</em> state.
166 *         <ul>
167 *         <li>An IllegalStateException is thrown if
168 *         setDataSource() is called in any other state.</li>
169 *         <li>It is good programming
170 *         practice to always look out for <code>IllegalArgumentException</code>
171 *         and <code>IOException</code> that may be thrown from the overloaded
172 *         <code>setDataSource</code> methods.</li>
173 *         </ul>
174 *         </li>
175 *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
176 *         before playback can be started.
177 *         <ul>
178 *         <li>There are two ways (synchronous vs.
179 *         asynchronous) that the <em>Prepared</em> state can be reached:
180 *         either a call to {@link #prepare()} (synchronous) which
181 *         transfers the object to the <em>Prepared</em> state once the method call
182 *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
183 *         first transfers the object to the <em>Preparing</em> state after the
184 *         call returns (which occurs almost right way) while the internal
185 *         player engine continues working on the rest of preparation work
186 *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
187 *         the internal player engine then calls a user supplied callback method,
188 *         onPrepared() of the OnPreparedListener interface, if an
189 *         OnPreparedListener is registered beforehand via {@link
190 *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
191 *         <li>It is important to note that
192 *         the <em>Preparing</em> state is a transient state, and the behavior
193 *         of calling any method with side effect while a MediaPlayer object is
194 *         in the <em>Preparing</em> state is undefined.</li>
195 *         <li>An IllegalStateException is
196 *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
197 *         any other state.</li>
198 *         <li>While in the <em>Prepared</em> state, properties
199 *         such as audio/sound volume, screenOnWhilePlaying, looping can be
200 *         adjusted by invoking the corresponding set methods.</li>
201 *         </ul>
202 *         </li>
203 *     <li>To start the playback, {@link #start()} must be called. After
204 *         {@link #start()} returns successfully, the MediaPlayer object is in the
205 *         <em>Started</em> state. {@link #isPlaying()} can be called to test
206 *         whether the MediaPlayer object is in the <em>Started</em> state.
207 *         <ul>
208 *         <li>While in the <em>Started</em> state, the internal player engine calls
209 *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
210 *         method if a OnBufferingUpdateListener has been registered beforehand
211 *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
212 *         This callback allows applications to keep track of the buffering status
213 *         while streaming audio/video.</li>
214 *         <li>Calling {@link #start()} has not effect
215 *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
216 *         </ul>
217 *         </li>
218 *     <li>Playback can be paused and stopped, and the current playback position
219 *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
220 *         {@link #pause()} returns, the MediaPlayer object enters the
221 *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
222 *         state to the <em>Paused</em> state and vice versa happens
223 *         asynchronously in the player engine. It may take some time before
224 *         the state is updated in calls to {@link #isPlaying()}, and it can be
225 *         a number of seconds in the case of streamed content.
226 *         <ul>
227 *         <li>Calling {@link #start()} to resume playback for a paused
228 *         MediaPlayer object, and the resumed playback
229 *         position is the same as where it was paused. When the call to
230 *         {@link #start()} returns, the paused MediaPlayer object goes back to
231 *         the <em>Started</em> state.</li>
232 *         <li>Calling {@link #pause()} has no effect on
233 *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
234 *         </ul>
235 *         </li>
236 *     <li>Calling  {@link #stop()} stops playback and causes a
237 *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
238 *         </em> or <em>PlaybackCompleted</em> state to enter the
239 *         <em>Stopped</em> state.
240 *         <ul>
241 *         <li>Once in the <em>Stopped</em> state, playback cannot be started
242 *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
243 *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
244 *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
245 *         object that is already in the <em>Stopped</em> state.</li>
246 *         </ul>
247 *         </li>
248 *     <li>The playback position can be adjusted with a call to
249 *         {@link #seekTo(int)}.
250 *         <ul>
251 *         <li>Although the asynchronuous {@link #seekTo(int)}
252 *         call returns right way, the actual seek operation may take a while to
253 *         finish, especially for audio/video being streamed. When the actual
254 *         seek operation completes, the internal player engine calls a user
255 *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
256 *         has been registered beforehand via
257 *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
258 *         <li>Please
259 *         note that {@link #seekTo(int)} can also be called in the other states,
260 *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
261 *         </em> state.</li>
262 *         <li>Furthermore, the actual current playback position
263 *         can be retrieved with a call to {@link #getCurrentPosition()}, which
264 *         is helpful for applications such as a Music player that need to keep
265 *         track of the playback progress.</li>
266 *         </ul>
267 *         </li>
268 *     <li>When the playback reaches the end of stream, the playback completes.
269 *         <ul>
270 *         <li>If the looping mode was being set to <var>true</var>with
271 *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
272 *         the <em>Started</em> state.</li>
273 *         <li>If the looping mode was set to <var>false
274 *         </var>, the player engine calls a user supplied callback method,
275 *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
276 *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
277 *         The invoke of the callback signals that the object is now in the <em>
278 *         PlaybackCompleted</em> state.</li>
279 *         <li>While in the <em>PlaybackCompleted</em>
280 *         state, calling {@link #start()} can restart the playback from the
281 *         beginning of the audio/video source.</li>
282 * </ul>
283 *
284 *
285 * <a name="Valid_and_Invalid_States"></a>
286 * <h3>Valid and invalid states</h3>
287 *
288 * <table border="0" cellspacing="0" cellpadding="0">
289 * <tr><td>Method Name </p></td>
290 *     <td>Valid Sates </p></td>
291 *     <td>Invalid States </p></td>
292 *     <td>Comments </p></td></tr>
293 * <tr><td>attachAuxEffect </p></td>
294 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
295 *     <td>{Idle, Error} </p></td>
296 *     <td>This method must be called after setDataSource.
297 *     Calling it does not change the object state. </p></td></tr>
298 * <tr><td>getAudioSessionId </p></td>
299 *     <td>any </p></td>
300 *     <td>{} </p></td>
301 *     <td>This method can be called in any state and calling it does not change
302 *         the object state. </p></td></tr>
303 * <tr><td>getCurrentPosition </p></td>
304 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
305 *         PlaybackCompleted} </p></td>
306 *     <td>{Error}</p></td>
307 *     <td>Successful invoke of this method in a valid state does not change the
308 *         state. Calling this method in an invalid state transfers the object
309 *         to the <em>Error</em> state. </p></td></tr>
310 * <tr><td>getDuration </p></td>
311 *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
312 *     <td>{Idle, Initialized, Error} </p></td>
313 *     <td>Successful invoke of this method in a valid state does not change the
314 *         state. Calling this method in an invalid state transfers the object
315 *         to the <em>Error</em> state. </p></td></tr>
316 * <tr><td>getVideoHeight </p></td>
317 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
318 *         PlaybackCompleted}</p></td>
319 *     <td>{Error}</p></td>
320 *     <td>Successful invoke of this method in a valid state does not change the
321 *         state. Calling this method in an invalid state transfers the object
322 *         to the <em>Error</em> state.  </p></td></tr>
323 * <tr><td>getVideoWidth </p></td>
324 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
325 *         PlaybackCompleted}</p></td>
326 *     <td>{Error}</p></td>
327 *     <td>Successful invoke of this method in a valid state does not change
328 *         the state. Calling this method in an invalid state transfers the
329 *         object to the <em>Error</em> state. </p></td></tr>
330 * <tr><td>isPlaying </p></td>
331 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
332 *          PlaybackCompleted}</p></td>
333 *     <td>{Error}</p></td>
334 *     <td>Successful invoke of this method in a valid state does not change
335 *         the state. Calling this method in an invalid state transfers the
336 *         object to the <em>Error</em> state. </p></td></tr>
337 * <tr><td>pause </p></td>
338 *     <td>{Started, Paused, PlaybackCompleted}</p></td>
339 *     <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td>
340 *     <td>Successful invoke of this method in a valid state transfers the
341 *         object to the <em>Paused</em> state. Calling this method in an
342 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
343 * <tr><td>prepare </p></td>
344 *     <td>{Initialized, Stopped} </p></td>
345 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
346 *     <td>Successful invoke of this method in a valid state transfers the
347 *         object to the <em>Prepared</em> state. Calling this method in an
348 *         invalid state throws an IllegalStateException.</p></td></tr>
349 * <tr><td>prepareAsync </p></td>
350 *     <td>{Initialized, Stopped} </p></td>
351 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
352 *     <td>Successful invoke of this method in a valid state transfers the
353 *         object to the <em>Preparing</em> state. Calling this method in an
354 *         invalid state throws an IllegalStateException.</p></td></tr>
355 * <tr><td>release </p></td>
356 *     <td>any </p></td>
357 *     <td>{} </p></td>
358 *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
359 * <tr><td>reset </p></td>
360 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
361 *         PlaybackCompleted, Error}</p></td>
362 *     <td>{}</p></td>
363 *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
364 * <tr><td>seekTo </p></td>
365 *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
366 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
367 *     <td>Successful invoke of this method in a valid state does not change
368 *         the state. Calling this method in an invalid state transfers the
369 *         object to the <em>Error</em> state. </p></td></tr>
370 * <tr><td>setAudioSessionId </p></td>
371 *     <td>{Idle} </p></td>
372 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
373 *          Error} </p></td>
374 *     <td>This method must be called in idle state as the audio session ID must be known before
375 *         calling setDataSource. Calling it does not change the object state. </p></td></tr>
376 * <tr><td>setAudioStreamType </p></td>
377 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
378 *          PlaybackCompleted}</p></td>
379 *     <td>{Error}</p></td>
380 *     <td>Successful invoke of this method does not change the state. In order for the
381 *         target audio stream type to become effective, this method must be called before
382 *         prepare() or prepareAsync().</p></td></tr>
383 * <tr><td>setAuxEffectSendLevel </p></td>
384 *     <td>any</p></td>
385 *     <td>{} </p></td>
386 *     <td>Calling this method does not change the object state. </p></td></tr>
387 * <tr><td>setDataSource </p></td>
388 *     <td>{Idle} </p></td>
389 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
390 *          Error} </p></td>
391 *     <td>Successful invoke of this method in a valid state transfers the
392 *         object to the <em>Initialized</em> state. Calling this method in an
393 *         invalid state throws an IllegalStateException.</p></td></tr>
394 * <tr><td>setDisplay </p></td>
395 *     <td>any </p></td>
396 *     <td>{} </p></td>
397 *     <td>This method can be called in any state and calling it does not change
398 *         the object state. </p></td></tr>
399 * <tr><td>setSurface </p></td>
400 *     <td>any </p></td>
401 *     <td>{} </p></td>
402 *     <td>This method can be called in any state and calling it does not change
403 *         the object state. </p></td></tr>
404 * <tr><td>setVideoScalingMode </p></td>
405 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
406 *     <td>{Idle, Error}</p></td>
407 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
408 * <tr><td>setLooping </p></td>
409 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
410 *         PlaybackCompleted}</p></td>
411 *     <td>{Error}</p></td>
412 *     <td>Successful invoke of this method in a valid state does not change
413 *         the state. Calling this method in an
414 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
415 * <tr><td>isLooping </p></td>
416 *     <td>any </p></td>
417 *     <td>{} </p></td>
418 *     <td>This method can be called in any state and calling it does not change
419 *         the object state. </p></td></tr>
420 * <tr><td>setOnBufferingUpdateListener </p></td>
421 *     <td>any </p></td>
422 *     <td>{} </p></td>
423 *     <td>This method can be called in any state and calling it does not change
424 *         the object state. </p></td></tr>
425 * <tr><td>setOnCompletionListener </p></td>
426 *     <td>any </p></td>
427 *     <td>{} </p></td>
428 *     <td>This method can be called in any state and calling it does not change
429 *         the object state. </p></td></tr>
430 * <tr><td>setOnErrorListener </p></td>
431 *     <td>any </p></td>
432 *     <td>{} </p></td>
433 *     <td>This method can be called in any state and calling it does not change
434 *         the object state. </p></td></tr>
435 * <tr><td>setOnPreparedListener </p></td>
436 *     <td>any </p></td>
437 *     <td>{} </p></td>
438 *     <td>This method can be called in any state and calling it does not change
439 *         the object state. </p></td></tr>
440 * <tr><td>setOnSeekCompleteListener </p></td>
441 *     <td>any </p></td>
442 *     <td>{} </p></td>
443 *     <td>This method can be called in any state and calling it does not change
444 *         the object state. </p></td></tr>
445 * <tr><td>setScreenOnWhilePlaying</></td>
446 *     <td>any </p></td>
447 *     <td>{} </p></td>
448 *     <td>This method can be called in any state and calling it does not change
449 *         the object state.  </p></td></tr>
450 * <tr><td>setVolume </p></td>
451 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
452 *          PlaybackCompleted}</p></td>
453 *     <td>{Error}</p></td>
454 *     <td>Successful invoke of this method does not change the state.
455 * <tr><td>setWakeMode </p></td>
456 *     <td>any </p></td>
457 *     <td>{} </p></td>
458 *     <td>This method can be called in any state and calling it does not change
459 *         the object state.</p></td></tr>
460 * <tr><td>start </p></td>
461 *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
462 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
463 *     <td>Successful invoke of this method in a valid state transfers the
464 *         object to the <em>Started</em> state. Calling this method in an
465 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
466 * <tr><td>stop </p></td>
467 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
468 *     <td>{Idle, Initialized, Error}</p></td>
469 *     <td>Successful invoke of this method in a valid state transfers the
470 *         object to the <em>Stopped</em> state. Calling this method in an
471 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
472 * <tr><td>getTrackInfo </p></td>
473 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
474 *     <td>{Idle, Initialized, Error}</p></td>
475 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
476 * <tr><td>addTimedTextSource </p></td>
477 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
478 *     <td>{Idle, Initialized, Error}</p></td>
479 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
480 * <tr><td>selectTrack </p></td>
481 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
482 *     <td>{Idle, Initialized, Error}</p></td>
483 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
484 * <tr><td>deselectTrack </p></td>
485 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
486 *     <td>{Idle, Initialized, Error}</p></td>
487 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
488 *
489 * </table>
490 *
491 * <a name="Permissions"></a>
492 * <h3>Permissions</h3>
493 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
494 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
495 * element.
496 *
497 * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
498 * when used with network-based content.
499 *
500 * <a name="Callbacks"></a>
501 * <h3>Callbacks</h3>
502 * <p>Applications may want to register for informational and error
503 * events in order to be informed of some internal state update and
504 * possible runtime errors during playback or streaming. Registration for
505 * these events is done by properly setting the appropriate listeners (via calls
506 * to
507 * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
508 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
509 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
510 * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
511 * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
512 * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
513 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
514 * In order to receive the respective callback
515 * associated with these listeners, applications are required to create
516 * MediaPlayer objects on a thread with its own Looper running (main UI
517 * thread by default has a Looper running).
518 *
519 */
520public class MediaPlayer
521{
522    /**
523       Constant to retrieve only the new metadata since the last
524       call.
525       // FIXME: unhide.
526       // FIXME: add link to getMetadata(boolean, boolean)
527       {@hide}
528     */
529    public static final boolean METADATA_UPDATE_ONLY = true;
530
531    /**
532       Constant to retrieve all the metadata.
533       // FIXME: unhide.
534       // FIXME: add link to getMetadata(boolean, boolean)
535       {@hide}
536     */
537    public static final boolean METADATA_ALL = false;
538
539    /**
540       Constant to enable the metadata filter during retrieval.
541       // FIXME: unhide.
542       // FIXME: add link to getMetadata(boolean, boolean)
543       {@hide}
544     */
545    public static final boolean APPLY_METADATA_FILTER = true;
546
547    /**
548       Constant to disable the metadata filter during retrieval.
549       // FIXME: unhide.
550       // FIXME: add link to getMetadata(boolean, boolean)
551       {@hide}
552     */
553    public static final boolean BYPASS_METADATA_FILTER = false;
554
555    static {
556        System.loadLibrary("media_jni");
557        native_init();
558    }
559
560    private final static String TAG = "MediaPlayer";
561    // Name of the remote interface for the media player. Must be kept
562    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
563    // macro invocation in IMediaPlayer.cpp
564    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
565
566    private int mNativeContext; // accessed by native methods
567    private int mNativeSurfaceTexture;  // accessed by native methods
568    private int mListenerContext; // accessed by native methods
569    private SurfaceHolder mSurfaceHolder;
570    private EventHandler mEventHandler;
571    private PowerManager.WakeLock mWakeLock = null;
572    private boolean mScreenOnWhilePlaying;
573    private boolean mStayAwake;
574
575    /**
576     * Default constructor. Consider using one of the create() methods for
577     * synchronously instantiating a MediaPlayer from a Uri or resource.
578     * <p>When done with the MediaPlayer, you should call  {@link #release()},
579     * to free the resources. If not released, too many MediaPlayer instances may
580     * result in an exception.</p>
581     */
582    public MediaPlayer() {
583
584        Looper looper;
585        if ((looper = Looper.myLooper()) != null) {
586            mEventHandler = new EventHandler(this, looper);
587        } else if ((looper = Looper.getMainLooper()) != null) {
588            mEventHandler = new EventHandler(this, looper);
589        } else {
590            mEventHandler = null;
591        }
592
593        /* Native setup requires a weak reference to our object.
594         * It's easier to create it here than in C++.
595         */
596        native_setup(new WeakReference<MediaPlayer>(this));
597    }
598
599    /*
600     * Update the MediaPlayer SurfaceTexture.
601     * Call after setting a new display surface.
602     */
603    private native void _setVideoSurface(Surface surface);
604
605    /* Do not change these values (starting with INVOKE_ID) without updating
606     * their counterparts in include/media/mediaplayer.h!
607     */
608    private static final int INVOKE_ID_GET_TRACK_INFO = 1;
609    private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
610    private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
611    private static final int INVOKE_ID_SELECT_TRACK = 4;
612    private static final int INVOKE_ID_DESELECT_TRACK = 5;
613    private static final int INVOKE_ID_SET_VIDEO_SCALE_MODE = 6;
614
615    /**
616     * Create a request parcel which can be routed to the native media
617     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
618     * returned has the proper InterfaceToken set. The caller should
619     * not overwrite that token, i.e it can only append data to the
620     * Parcel.
621     *
622     * @return A parcel suitable to hold a request for the native
623     * player.
624     * {@hide}
625     */
626    public Parcel newRequest() {
627        Parcel parcel = Parcel.obtain();
628        parcel.writeInterfaceToken(IMEDIA_PLAYER);
629        return parcel;
630    }
631
632    /**
633     * Invoke a generic method on the native player using opaque
634     * parcels for the request and reply. Both payloads' format is a
635     * convention between the java caller and the native player.
636     * Must be called after setDataSource to make sure a native player
637     * exists. On failure, a RuntimeException is thrown.
638     *
639     * @param request Parcel with the data for the extension. The
640     * caller must use {@link #newRequest()} to get one.
641     *
642     * @param reply Output parcel with the data returned by the
643     * native player.
644     * {@hide}
645     */
646    public void invoke(Parcel request, Parcel reply) {
647        int retcode = native_invoke(request, reply);
648        reply.setDataPosition(0);
649        if (retcode != 0) {
650            throw new RuntimeException("failure code: " + retcode);
651        }
652    }
653
654    /**
655     * Sets the {@link SurfaceHolder} to use for displaying the video
656     * portion of the media.
657     *
658     * Either a surface holder or surface must be set if a display or video sink
659     * is needed.  Not calling this method or {@link #setSurface(Surface)}
660     * when playing back a video will result in only the audio track being played.
661     * A null surface holder or surface will result in only the audio track being
662     * played.
663     *
664     * @param sh the SurfaceHolder to use for video display
665     */
666    public void setDisplay(SurfaceHolder sh) {
667        mSurfaceHolder = sh;
668        Surface surface;
669        if (sh != null) {
670            surface = sh.getSurface();
671        } else {
672            surface = null;
673        }
674        _setVideoSurface(surface);
675        updateSurfaceScreenOn();
676    }
677
678    /**
679     * Sets the {@link Surface} to be used as the sink for the video portion of
680     * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but
681     * does not support {@link #setScreenOnWhilePlaying(boolean)}.  Setting a
682     * Surface will un-set any Surface or SurfaceHolder that was previously set.
683     * A null surface will result in only the audio track being played.
684     *
685     * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
686     * returned from {@link SurfaceTexture#getTimestamp()} will have an
687     * unspecified zero point.  These timestamps cannot be directly compared
688     * between different media sources, different instances of the same media
689     * source, or multiple runs of the same program.  The timestamp is normally
690     * monotonically increasing and is unaffected by time-of-day adjustments,
691     * but it is reset when the position is set.
692     *
693     * @param surface The {@link Surface} to be used for the video portion of
694     * the media.
695     */
696    public void setSurface(Surface surface) {
697        if (mScreenOnWhilePlaying && surface != null) {
698            Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
699        }
700        mSurfaceHolder = null;
701        _setVideoSurface(surface);
702        updateSurfaceScreenOn();
703    }
704
705    /* Do not change these video scaling mode values below without updating
706     * their counterparts in system/window.h! Please do not forget to update
707     * {@link #isVideoScalingModeSupported} when new video scaling modes
708     * are added.
709     */
710    /**
711     * Specifies a video scaling mode. The content is stretched to the
712     * surface rendering area. When the surface has the same aspect ratio
713     * as the content, the aspect ratio of the content is maintained;
714     * otherwise, the aspect ratio of the content is not maintained when video
715     * is being rendered. Unlike {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING},
716     * there is no content cropping with this video scaling mode.
717     */
718    public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
719
720    /**
721     * Specifies a video scaling mode. The content is scaled, maintaining
722     * its aspect ratio. The whole surface area is always used. When the
723     * aspect ratio of the content is the same as the surface, no content
724     * is cropped; otherwise, content is cropped to fit the surface.
725     */
726    public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2;
727    /**
728     * Sets video scaling mode. To make the target video scaling mode
729     * effective during playback, this method must be called after
730     * data source is set. If not called, the default video
731     * scaling mode is {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}.
732     *
733     * <p> The supported video scaling modes are:
734     * <ul>
735     * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}
736     * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}
737     * </ul>
738     *
739     * @param mode target video scaling mode. Most be one of the supported
740     * video scaling modes; otherwise, IllegalArgumentException will be thrown.
741     *
742     * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT
743     * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
744     */
745    public void setVideoScalingMode(int mode) {
746        if (!isVideoScalingModeSupported(mode)) {
747            final String msg = "Scaling mode " + mode + " is not supported";
748            throw new IllegalArgumentException(msg);
749        }
750        Parcel request = Parcel.obtain();
751        Parcel reply = Parcel.obtain();
752        try {
753            request.writeInterfaceToken(IMEDIA_PLAYER);
754            request.writeInt(INVOKE_ID_SET_VIDEO_SCALE_MODE);
755            request.writeInt(mode);
756            invoke(request, reply);
757        } finally {
758            request.recycle();
759            reply.recycle();
760        }
761    }
762
763    /**
764     * Convenience method to create a MediaPlayer for a given Uri.
765     * On success, {@link #prepare()} will already have been called and must not be called again.
766     * <p>When done with the MediaPlayer, you should call  {@link #release()},
767     * to free the resources. If not released, too many MediaPlayer instances will
768     * result in an exception.</p>
769     *
770     * @param context the Context to use
771     * @param uri the Uri from which to get the datasource
772     * @return a MediaPlayer object, or null if creation failed
773     */
774    public static MediaPlayer create(Context context, Uri uri) {
775        return create (context, uri, null);
776    }
777
778    /**
779     * Convenience method to create a MediaPlayer for a given Uri.
780     * On success, {@link #prepare()} will already have been called and must not be called again.
781     * <p>When done with the MediaPlayer, you should call  {@link #release()},
782     * to free the resources. If not released, too many MediaPlayer instances will
783     * result in an exception.</p>
784     *
785     * @param context the Context to use
786     * @param uri the Uri from which to get the datasource
787     * @param holder the SurfaceHolder to use for displaying the video
788     * @return a MediaPlayer object, or null if creation failed
789     */
790    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
791
792        try {
793            MediaPlayer mp = new MediaPlayer();
794            mp.setDataSource(context, uri);
795            if (holder != null) {
796                mp.setDisplay(holder);
797            }
798            mp.prepare();
799            return mp;
800        } catch (IOException ex) {
801            Log.d(TAG, "create failed:", ex);
802            // fall through
803        } catch (IllegalArgumentException ex) {
804            Log.d(TAG, "create failed:", ex);
805            // fall through
806        } catch (SecurityException ex) {
807            Log.d(TAG, "create failed:", ex);
808            // fall through
809        }
810
811        return null;
812    }
813
814    // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
815
816    /**
817     * Convenience method to create a MediaPlayer for a given resource id.
818     * On success, {@link #prepare()} will already have been called and must not be called again.
819     * <p>When done with the MediaPlayer, you should call  {@link #release()},
820     * to free the resources. If not released, too many MediaPlayer instances will
821     * result in an exception.</p>
822     *
823     * @param context the Context to use
824     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
825     *              the resource to use as the datasource
826     * @return a MediaPlayer object, or null if creation failed
827     */
828    public static MediaPlayer create(Context context, int resid) {
829        try {
830            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
831            if (afd == null) return null;
832
833            MediaPlayer mp = new MediaPlayer();
834            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
835            afd.close();
836            mp.prepare();
837            return mp;
838        } catch (IOException ex) {
839            Log.d(TAG, "create failed:", ex);
840            // fall through
841        } catch (IllegalArgumentException ex) {
842            Log.d(TAG, "create failed:", ex);
843           // fall through
844        } catch (SecurityException ex) {
845            Log.d(TAG, "create failed:", ex);
846            // fall through
847        }
848        return null;
849    }
850
851    /**
852     * Sets the data source as a content Uri.
853     *
854     * @param context the Context to use when resolving the Uri
855     * @param uri the Content URI of the data you want to play
856     * @throws IllegalStateException if it is called in an invalid state
857     */
858    public void setDataSource(Context context, Uri uri)
859        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
860        setDataSource(context, uri, null);
861    }
862
863    /**
864     * Sets the data source as a content Uri.
865     *
866     * @param context the Context to use when resolving the Uri
867     * @param uri the Content URI of the data you want to play
868     * @param headers the headers to be sent together with the request for the data
869     * @throws IllegalStateException if it is called in an invalid state
870     */
871    public void setDataSource(Context context, Uri uri, Map<String, String> headers)
872        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
873        disableProxyListener();
874
875        String scheme = uri.getScheme();
876        if(scheme == null || scheme.equals("file")) {
877            setDataSource(uri.getPath());
878            return;
879        }
880
881        AssetFileDescriptor fd = null;
882        try {
883            ContentResolver resolver = context.getContentResolver();
884            fd = resolver.openAssetFileDescriptor(uri, "r");
885            if (fd == null) {
886                return;
887            }
888            // Note: using getDeclaredLength so that our behavior is the same
889            // as previous versions when the content provider is returning
890            // a full file.
891            if (fd.getDeclaredLength() < 0) {
892                setDataSource(fd.getFileDescriptor());
893            } else {
894                setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
895            }
896            return;
897        } catch (SecurityException ex) {
898        } catch (IOException ex) {
899        } finally {
900            if (fd != null) {
901                fd.close();
902            }
903        }
904
905        Log.d(TAG, "Couldn't open file on client side, trying server side");
906
907        setDataSource(uri.toString(), headers);
908
909        if (scheme.equalsIgnoreCase("http")
910                || scheme.equalsIgnoreCase("https")) {
911            setupProxyListener(context);
912        }
913    }
914
915    /**
916     * Sets the data source (file-path or http/rtsp URL) to use.
917     *
918     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
919     * @throws IllegalStateException if it is called in an invalid state
920     *
921     * <p>When <code>path</code> refers to a local file, the file may actually be opened by a
922     * process other than the calling application.  This implies that the pathname
923     * should be an absolute path (as any other process runs with unspecified current working
924     * directory), and that the pathname should reference a world-readable file.
925     * As an alternative, the application could first open the file for reading,
926     * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}.
927     */
928    public void setDataSource(String path)
929            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
930        setDataSource(path, null, null);
931    }
932
933    /**
934     * Sets the data source (file-path or http/rtsp URL) to use.
935     *
936     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
937     * @param headers the headers associated with the http request for the stream you want to play
938     * @throws IllegalStateException if it is called in an invalid state
939     * @hide pending API council
940     */
941    public void setDataSource(String path, Map<String, String> headers)
942            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
943    {
944        String[] keys = null;
945        String[] values = null;
946
947        if (headers != null) {
948            keys = new String[headers.size()];
949            values = new String[headers.size()];
950
951            int i = 0;
952            for (Map.Entry<String, String> entry: headers.entrySet()) {
953                keys[i] = entry.getKey();
954                values[i] = entry.getValue();
955                ++i;
956            }
957        }
958        setDataSource(path, keys, values);
959    }
960
961    private void setDataSource(String path, String[] keys, String[] values)
962            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
963        disableProxyListener();
964
965        final Uri uri = Uri.parse(path);
966        if ("file".equals(uri.getScheme())) {
967            path = uri.getPath();
968        }
969
970        final File file = new File(path);
971        if (file.exists()) {
972            FileInputStream is = new FileInputStream(file);
973            FileDescriptor fd = is.getFD();
974            setDataSource(fd);
975            is.close();
976        } else {
977            _setDataSource(path, keys, values);
978        }
979    }
980
981    private native void _setDataSource(
982        String path, String[] keys, String[] values)
983        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
984
985    /**
986     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
987     * to close the file descriptor. It is safe to do so as soon as this call returns.
988     *
989     * @param fd the FileDescriptor for the file you want to play
990     * @throws IllegalStateException if it is called in an invalid state
991     */
992    public void setDataSource(FileDescriptor fd)
993            throws IOException, IllegalArgumentException, IllegalStateException {
994        // intentionally less than LONG_MAX
995        setDataSource(fd, 0, 0x7ffffffffffffffL);
996    }
997
998    /**
999     * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
1000     * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
1001     * to close the file descriptor. It is safe to do so as soon as this call returns.
1002     *
1003     * @param fd the FileDescriptor for the file you want to play
1004     * @param offset the offset into the file where the data to be played starts, in bytes
1005     * @param length the length in bytes of the data to be played
1006     * @throws IllegalStateException if it is called in an invalid state
1007     */
1008    public void setDataSource(FileDescriptor fd, long offset, long length)
1009            throws IOException, IllegalArgumentException, IllegalStateException {
1010        disableProxyListener();
1011        _setDataSource(fd, offset, length);
1012    }
1013
1014    private native void _setDataSource(FileDescriptor fd, long offset, long length)
1015            throws IOException, IllegalArgumentException, IllegalStateException;
1016
1017    /**
1018     * Prepares the player for playback, synchronously.
1019     *
1020     * After setting the datasource and the display surface, you need to either
1021     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
1022     * which blocks until MediaPlayer is ready for playback.
1023     *
1024     * @throws IllegalStateException if it is called in an invalid state
1025     */
1026    public native void prepare() throws IOException, IllegalStateException;
1027
1028    /**
1029     * Prepares the player for playback, asynchronously.
1030     *
1031     * After setting the datasource and the display surface, you need to either
1032     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
1033     * which returns immediately, rather than blocking until enough data has been
1034     * buffered.
1035     *
1036     * @throws IllegalStateException if it is called in an invalid state
1037     */
1038    public native void prepareAsync() throws IllegalStateException;
1039
1040    /**
1041     * Starts or resumes playback. If playback had previously been paused,
1042     * playback will continue from where it was paused. If playback had
1043     * been stopped, or never started before, playback will start at the
1044     * beginning.
1045     *
1046     * @throws IllegalStateException if it is called in an invalid state
1047     */
1048    public  void start() throws IllegalStateException {
1049        stayAwake(true);
1050        _start();
1051    }
1052
1053    private native void _start() throws IllegalStateException;
1054
1055    /**
1056     * Stops playback after playback has been stopped or paused.
1057     *
1058     * @throws IllegalStateException if the internal player engine has not been
1059     * initialized.
1060     */
1061    public void stop() throws IllegalStateException {
1062        stayAwake(false);
1063        _stop();
1064    }
1065
1066    private native void _stop() throws IllegalStateException;
1067
1068    /**
1069     * Pauses playback. Call start() to resume.
1070     *
1071     * @throws IllegalStateException if the internal player engine has not been
1072     * initialized.
1073     */
1074    public void pause() throws IllegalStateException {
1075        stayAwake(false);
1076        _pause();
1077    }
1078
1079    private native void _pause() throws IllegalStateException;
1080
1081    /**
1082     * Set the low-level power management behavior for this MediaPlayer.  This
1083     * can be used when the MediaPlayer is not playing through a SurfaceHolder
1084     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
1085     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
1086     *
1087     * <p>This function has the MediaPlayer access the low-level power manager
1088     * service to control the device's power usage while playing is occurring.
1089     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
1090     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
1091     * permission.
1092     * By default, no attempt is made to keep the device awake during playback.
1093     *
1094     * @param context the Context to use
1095     * @param mode    the power/wake mode to set
1096     * @see android.os.PowerManager
1097     */
1098    public void setWakeMode(Context context, int mode) {
1099        boolean washeld = false;
1100        if (mWakeLock != null) {
1101            if (mWakeLock.isHeld()) {
1102                washeld = true;
1103                mWakeLock.release();
1104            }
1105            mWakeLock = null;
1106        }
1107
1108        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1109        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
1110        mWakeLock.setReferenceCounted(false);
1111        if (washeld) {
1112            mWakeLock.acquire();
1113        }
1114    }
1115
1116    /**
1117     * Control whether we should use the attached SurfaceHolder to keep the
1118     * screen on while video playback is occurring.  This is the preferred
1119     * method over {@link #setWakeMode} where possible, since it doesn't
1120     * require that the application have permission for low-level wake lock
1121     * access.
1122     *
1123     * @param screenOn Supply true to keep the screen on, false to allow it
1124     * to turn off.
1125     */
1126    public void setScreenOnWhilePlaying(boolean screenOn) {
1127        if (mScreenOnWhilePlaying != screenOn) {
1128            if (screenOn && mSurfaceHolder == null) {
1129                Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
1130            }
1131            mScreenOnWhilePlaying = screenOn;
1132            updateSurfaceScreenOn();
1133        }
1134    }
1135
1136    private void stayAwake(boolean awake) {
1137        if (mWakeLock != null) {
1138            if (awake && !mWakeLock.isHeld()) {
1139                mWakeLock.acquire();
1140            } else if (!awake && mWakeLock.isHeld()) {
1141                mWakeLock.release();
1142            }
1143        }
1144        mStayAwake = awake;
1145        updateSurfaceScreenOn();
1146    }
1147
1148    private void updateSurfaceScreenOn() {
1149        if (mSurfaceHolder != null) {
1150            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1151        }
1152    }
1153
1154    /**
1155     * Returns the width of the video.
1156     *
1157     * @return the width of the video, or 0 if there is no video,
1158     * no display surface was set, or the width has not been determined
1159     * yet. The OnVideoSizeChangedListener can be registered via
1160     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1161     * to provide a notification when the width is available.
1162     */
1163    public native int getVideoWidth();
1164
1165    /**
1166     * Returns the height of the video.
1167     *
1168     * @return the height of the video, or 0 if there is no video,
1169     * no display surface was set, or the height has not been determined
1170     * yet. The OnVideoSizeChangedListener can be registered via
1171     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1172     * to provide a notification when the height is available.
1173     */
1174    public native int getVideoHeight();
1175
1176    /**
1177     * Checks whether the MediaPlayer is playing.
1178     *
1179     * @return true if currently playing, false otherwise
1180     * @throws IllegalStateException if the internal player engine has not been
1181     * initialized or has been released.
1182     */
1183    public native boolean isPlaying();
1184
1185    /**
1186     * Seeks to specified time position.
1187     *
1188     * @param msec the offset in milliseconds from the start to seek to
1189     * @throws IllegalStateException if the internal player engine has not been
1190     * initialized
1191     */
1192    public native void seekTo(int msec) throws IllegalStateException;
1193
1194    /**
1195     * Gets the current playback position.
1196     *
1197     * @return the current position in milliseconds
1198     */
1199    public native int getCurrentPosition();
1200
1201    /**
1202     * Gets the duration of the file.
1203     *
1204     * @return the duration in milliseconds, if no duration is available
1205     *         (for example, if streaming live content), -1 is returned.
1206     */
1207    public native int getDuration();
1208
1209    /**
1210     * Gets the media metadata.
1211     *
1212     * @param update_only controls whether the full set of available
1213     * metadata is returned or just the set that changed since the
1214     * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1215     * #METADATA_ALL}.
1216     *
1217     * @param apply_filter if true only metadata that matches the
1218     * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1219     * #BYPASS_METADATA_FILTER}.
1220     *
1221     * @return The metadata, possibly empty. null if an error occured.
1222     // FIXME: unhide.
1223     * {@hide}
1224     */
1225    public Metadata getMetadata(final boolean update_only,
1226                                final boolean apply_filter) {
1227        Parcel reply = Parcel.obtain();
1228        Metadata data = new Metadata();
1229
1230        if (!native_getMetadata(update_only, apply_filter, reply)) {
1231            reply.recycle();
1232            return null;
1233        }
1234
1235        // Metadata takes over the parcel, don't recycle it unless
1236        // there is an error.
1237        if (!data.parse(reply)) {
1238            reply.recycle();
1239            return null;
1240        }
1241        return data;
1242    }
1243
1244    /**
1245     * Set a filter for the metadata update notification and update
1246     * retrieval. The caller provides 2 set of metadata keys, allowed
1247     * and blocked. The blocked set always takes precedence over the
1248     * allowed one.
1249     * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
1250     * shorthands to allow/block all or no metadata.
1251     *
1252     * By default, there is no filter set.
1253     *
1254     * @param allow Is the set of metadata the client is interested
1255     *              in receiving new notifications for.
1256     * @param block Is the set of metadata the client is not interested
1257     *              in receiving new notifications for.
1258     * @return The call status code.
1259     *
1260     // FIXME: unhide.
1261     * {@hide}
1262     */
1263    public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1264        // Do our serialization manually instead of calling
1265        // Parcel.writeArray since the sets are made of the same type
1266        // we avoid paying the price of calling writeValue (used by
1267        // writeArray) which burns an extra int per element to encode
1268        // the type.
1269        Parcel request =  newRequest();
1270
1271        // The parcel starts already with an interface token. There
1272        // are 2 filters. Each one starts with a 4bytes number to
1273        // store the len followed by a number of int (4 bytes as well)
1274        // representing the metadata type.
1275        int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1276
1277        if (request.dataCapacity() < capacity) {
1278            request.setDataCapacity(capacity);
1279        }
1280
1281        request.writeInt(allow.size());
1282        for(Integer t: allow) {
1283            request.writeInt(t);
1284        }
1285        request.writeInt(block.size());
1286        for(Integer t: block) {
1287            request.writeInt(t);
1288        }
1289        return native_setMetadataFilter(request);
1290    }
1291
1292    /**
1293     * Set the MediaPlayer to start when this MediaPlayer finishes playback
1294     * (i.e. reaches the end of the stream).
1295     * The media framework will attempt to transition from this player to
1296     * the next as seamlessly as possible. The next player can be set at
1297     * any time before completion. The next player must be prepared by the
1298     * app, and the application should not call start() on it.
1299     * The next MediaPlayer must be different from 'this'. An exception
1300     * will be thrown if next == this.
1301     * The application may call setNextMediaPlayer(null) to indicate no
1302     * next player should be started at the end of playback.
1303     * If the current player is looping, it will keep looping and the next
1304     * player will not be started.
1305     *
1306     * @param next the player to start after this one completes playback.
1307     *
1308     */
1309    public native void setNextMediaPlayer(MediaPlayer next);
1310
1311    /**
1312     * Releases resources associated with this MediaPlayer object.
1313     * It is considered good practice to call this method when you're
1314     * done using the MediaPlayer. In particular, whenever an Activity
1315     * of an application is paused (its onPause() method is called),
1316     * or stopped (its onStop() method is called), this method should be
1317     * invoked to release the MediaPlayer object, unless the application
1318     * has a special need to keep the object around. In addition to
1319     * unnecessary resources (such as memory and instances of codecs)
1320     * being held, failure to call this method immediately if a
1321     * MediaPlayer object is no longer needed may also lead to
1322     * continuous battery consumption for mobile devices, and playback
1323     * failure for other applications if no multiple instances of the
1324     * same codec are supported on a device. Even if multiple instances
1325     * of the same codec are supported, some performance degradation
1326     * may be expected when unnecessary multiple instances are used
1327     * at the same time.
1328     */
1329    public void release() {
1330        stayAwake(false);
1331        updateSurfaceScreenOn();
1332        mOnPreparedListener = null;
1333        mOnBufferingUpdateListener = null;
1334        mOnCompletionListener = null;
1335        mOnSeekCompleteListener = null;
1336        mOnErrorListener = null;
1337        mOnInfoListener = null;
1338        mOnVideoSizeChangedListener = null;
1339        mOnTimedTextListener = null;
1340        mOnSubtitleDataListener = null;
1341        _release();
1342    }
1343
1344    private native void _release();
1345
1346    /**
1347     * Resets the MediaPlayer to its uninitialized state. After calling
1348     * this method, you will have to initialize it again by setting the
1349     * data source and calling prepare().
1350     */
1351    public void reset() {
1352        stayAwake(false);
1353        _reset();
1354        // make sure none of the listeners get called anymore
1355        mEventHandler.removeCallbacksAndMessages(null);
1356
1357        disableProxyListener();
1358    }
1359
1360    private native void _reset();
1361
1362    /**
1363     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1364     * for a list of stream types. Must call this method before prepare() or
1365     * prepareAsync() in order for the target stream type to become effective
1366     * thereafter.
1367     *
1368     * @param streamtype the audio stream type
1369     * @see android.media.AudioManager
1370     */
1371    public native void setAudioStreamType(int streamtype);
1372
1373    /**
1374     * Sets the player to be looping or non-looping.
1375     *
1376     * @param looping whether to loop or not
1377     */
1378    public native void setLooping(boolean looping);
1379
1380    /**
1381     * Checks whether the MediaPlayer is looping or non-looping.
1382     *
1383     * @return true if the MediaPlayer is currently looping, false otherwise
1384     */
1385    public native boolean isLooping();
1386
1387    /**
1388     * Sets the volume on this player.
1389     * This API is recommended for balancing the output of audio streams
1390     * within an application. Unless you are writing an application to
1391     * control user settings, this API should be used in preference to
1392     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
1393     * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
1394     * UI controls should be scaled logarithmically.
1395     *
1396     * @param leftVolume left volume scalar
1397     * @param rightVolume right volume scalar
1398     */
1399    /*
1400     * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
1401     * The single parameter form below is preferred if the channel volumes don't need
1402     * to be set independently.
1403     */
1404    public native void setVolume(float leftVolume, float rightVolume);
1405
1406    /**
1407     * Similar, excepts sets volume of all channels to same value.
1408     * @hide
1409     */
1410    public void setVolume(float volume) {
1411        setVolume(volume, volume);
1412    }
1413
1414    /**
1415     * Sets the audio session ID.
1416     *
1417     * @param sessionId the audio session ID.
1418     * The audio session ID is a system wide unique identifier for the audio stream played by
1419     * this MediaPlayer instance.
1420     * The primary use of the audio session ID  is to associate audio effects to a particular
1421     * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1422     * this effect will be applied only to the audio content of media players within the same
1423     * audio session and not to the output mix.
1424     * When created, a MediaPlayer instance automatically generates its own audio session ID.
1425     * However, it is possible to force this player to be part of an already existing audio session
1426     * by calling this method.
1427     * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1428     * @throws IllegalStateException if it is called in an invalid state
1429     */
1430    public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
1431
1432    /**
1433     * Returns the audio session ID.
1434     *
1435     * @return the audio session ID. {@see #setAudioSessionId(int)}
1436     * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
1437     */
1438    public native int getAudioSessionId();
1439
1440    /**
1441     * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1442     * effect which can be applied on any sound source that directs a certain amount of its
1443     * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1444     * {@see #setAuxEffectSendLevel(float)}.
1445     * <p>After creating an auxiliary effect (e.g.
1446     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1447     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1448     * to attach the player to the effect.
1449     * <p>To detach the effect from the player, call this method with a null effect id.
1450     * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1451     * methods.
1452     * @param effectId system wide unique id of the effect to attach
1453     */
1454    public native void attachAuxEffect(int effectId);
1455
1456
1457    /**
1458     * Sets the send level of the player to the attached auxiliary effect
1459     * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1460     * <p>By default the send level is 0, so even if an effect is attached to the player
1461     * this method must be called for the effect to be applied.
1462     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1463     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1464     * so an appropriate conversion from linear UI input x to level is:
1465     * x == 0 -> level = 0
1466     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1467     * @param level send level scalar
1468     */
1469    public native void setAuxEffectSendLevel(float level);
1470
1471    /*
1472     * @param request Parcel destinated to the media player. The
1473     *                Interface token must be set to the IMediaPlayer
1474     *                one to be routed correctly through the system.
1475     * @param reply[out] Parcel that will contain the reply.
1476     * @return The status code.
1477     */
1478    private native final int native_invoke(Parcel request, Parcel reply);
1479
1480
1481    /*
1482     * @param update_only If true fetch only the set of metadata that have
1483     *                    changed since the last invocation of getMetadata.
1484     *                    The set is built using the unfiltered
1485     *                    notifications the native player sent to the
1486     *                    MediaPlayerService during that period of
1487     *                    time. If false, all the metadatas are considered.
1488     * @param apply_filter  If true, once the metadata set has been built based on
1489     *                     the value update_only, the current filter is applied.
1490     * @param reply[out] On return contains the serialized
1491     *                   metadata. Valid only if the call was successful.
1492     * @return The status code.
1493     */
1494    private native final boolean native_getMetadata(boolean update_only,
1495                                                    boolean apply_filter,
1496                                                    Parcel reply);
1497
1498    /*
1499     * @param request Parcel with the 2 serialized lists of allowed
1500     *                metadata types followed by the one to be
1501     *                dropped. Each list starts with an integer
1502     *                indicating the number of metadata type elements.
1503     * @return The status code.
1504     */
1505    private native final int native_setMetadataFilter(Parcel request);
1506
1507    private static native final void native_init();
1508    private native final void native_setup(Object mediaplayer_this);
1509    private native final void native_finalize();
1510
1511    /**
1512     * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
1513     *
1514     * @see android.media.MediaPlayer#getTrackInfo
1515     */
1516    static public class TrackInfo implements Parcelable {
1517        /**
1518         * Gets the track type.
1519         * @return TrackType which indicates if the track is video, audio, timed text.
1520         */
1521        public int getTrackType() {
1522            return mTrackType;
1523        }
1524
1525        /**
1526         * Gets the language code of the track.
1527         * @return a language code in either way of ISO-639-1 or ISO-639-2.
1528         * When the language is unknown or could not be determined,
1529         * ISO-639-2 language code, "und", is returned.
1530         */
1531        public String getLanguage() {
1532            String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
1533            return language == null ? "und" : language;
1534        }
1535
1536        /**
1537         * Gets the {@link MediaFormat} of the track.  If the format is
1538         * unknown or could not be determined, null is returned.
1539         */
1540        public MediaFormat getFormat() {
1541            if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1542                return mFormat;
1543            }
1544            return null;
1545        }
1546
1547        public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
1548        public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
1549        public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
1550        public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
1551        /** @hide */
1552        public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
1553
1554        final int mTrackType;
1555        final MediaFormat mFormat;
1556
1557        TrackInfo(Parcel in) {
1558            mTrackType = in.readInt();
1559            // TODO: parcel in the full MediaFormat
1560            String language = in.readString();
1561
1562            if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1563                mFormat = MediaFormat.createSubtitleFormat(
1564                    MEDIA_MIMETYPE_TEXT_SUBRIP, language);
1565            } else {
1566                mFormat = new MediaFormat();
1567                mFormat.setString(MediaFormat.KEY_LANGUAGE, language);
1568            }
1569        }
1570
1571        /**
1572         * {@inheritDoc}
1573         */
1574        @Override
1575        public int describeContents() {
1576            return 0;
1577        }
1578
1579        /**
1580         * {@inheritDoc}
1581         */
1582        @Override
1583        public void writeToParcel(Parcel dest, int flags) {
1584            dest.writeInt(mTrackType);
1585            dest.writeString(getLanguage());
1586        }
1587
1588        /**
1589         * Used to read a TrackInfo from a Parcel.
1590         */
1591        static final Parcelable.Creator<TrackInfo> CREATOR
1592                = new Parcelable.Creator<TrackInfo>() {
1593                    @Override
1594                    public TrackInfo createFromParcel(Parcel in) {
1595                        return new TrackInfo(in);
1596                    }
1597
1598                    @Override
1599                    public TrackInfo[] newArray(int size) {
1600                        return new TrackInfo[size];
1601                    }
1602                };
1603
1604    };
1605
1606    /**
1607     * Returns an array of track information.
1608     *
1609     * @return Array of track info. The total number of tracks is the array length.
1610     * Must be called again if an external timed text source has been added after any of the
1611     * addTimedTextSource methods are called.
1612     * @throws IllegalStateException if it is called in an invalid state.
1613     */
1614    public TrackInfo[] getTrackInfo() throws IllegalStateException {
1615        Parcel request = Parcel.obtain();
1616        Parcel reply = Parcel.obtain();
1617        try {
1618            request.writeInterfaceToken(IMEDIA_PLAYER);
1619            request.writeInt(INVOKE_ID_GET_TRACK_INFO);
1620            invoke(request, reply);
1621            TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
1622            return trackInfo;
1623        } finally {
1624            request.recycle();
1625            reply.recycle();
1626        }
1627    }
1628
1629    /* Do not change these values without updating their counterparts
1630     * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
1631     */
1632    /**
1633     * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
1634     */
1635    public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
1636
1637    /*
1638     * A helper function to check if the mime type is supported by media framework.
1639     */
1640    private static boolean availableMimeTypeForExternalSource(String mimeType) {
1641        if (mimeType == MEDIA_MIMETYPE_TEXT_SUBRIP) {
1642            return true;
1643        }
1644        return false;
1645    }
1646
1647    /* TODO: Limit the total number of external timed text source to a reasonable number.
1648     */
1649    /**
1650     * Adds an external timed text source file.
1651     *
1652     * Currently supported format is SubRip with the file extension .srt, case insensitive.
1653     * Note that a single external timed text source may contain multiple tracks in it.
1654     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1655     * additional tracks become available after this method call.
1656     *
1657     * @param path The file path of external timed text source file.
1658     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1659     * @throws IOException if the file cannot be accessed or is corrupted.
1660     * @throws IllegalArgumentException if the mimeType is not supported.
1661     * @throws IllegalStateException if called in an invalid state.
1662     */
1663    public void addTimedTextSource(String path, String mimeType)
1664            throws IOException, IllegalArgumentException, IllegalStateException {
1665        if (!availableMimeTypeForExternalSource(mimeType)) {
1666            final String msg = "Illegal mimeType for timed text source: " + mimeType;
1667            throw new IllegalArgumentException(msg);
1668        }
1669
1670        File file = new File(path);
1671        if (file.exists()) {
1672            FileInputStream is = new FileInputStream(file);
1673            FileDescriptor fd = is.getFD();
1674            addTimedTextSource(fd, mimeType);
1675            is.close();
1676        } else {
1677            // We do not support the case where the path is not a file.
1678            throw new IOException(path);
1679        }
1680    }
1681
1682    /**
1683     * Adds an external timed text source file (Uri).
1684     *
1685     * Currently supported format is SubRip with the file extension .srt, case insensitive.
1686     * Note that a single external timed text source may contain multiple tracks in it.
1687     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1688     * additional tracks become available after this method call.
1689     *
1690     * @param context the Context to use when resolving the Uri
1691     * @param uri the Content URI of the data you want to play
1692     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1693     * @throws IOException if the file cannot be accessed or is corrupted.
1694     * @throws IllegalArgumentException if the mimeType is not supported.
1695     * @throws IllegalStateException if called in an invalid state.
1696     */
1697    public void addTimedTextSource(Context context, Uri uri, String mimeType)
1698            throws IOException, IllegalArgumentException, IllegalStateException {
1699        String scheme = uri.getScheme();
1700        if(scheme == null || scheme.equals("file")) {
1701            addTimedTextSource(uri.getPath(), mimeType);
1702            return;
1703        }
1704
1705        AssetFileDescriptor fd = null;
1706        try {
1707            ContentResolver resolver = context.getContentResolver();
1708            fd = resolver.openAssetFileDescriptor(uri, "r");
1709            if (fd == null) {
1710                return;
1711            }
1712            addTimedTextSource(fd.getFileDescriptor(), mimeType);
1713            return;
1714        } catch (SecurityException ex) {
1715        } catch (IOException ex) {
1716        } finally {
1717            if (fd != null) {
1718                fd.close();
1719            }
1720        }
1721    }
1722
1723    /**
1724     * Adds an external timed text source file (FileDescriptor).
1725     *
1726     * It is the caller's responsibility to close the file descriptor.
1727     * It is safe to do so as soon as this call returns.
1728     *
1729     * Currently supported format is SubRip. Note that a single external timed text source may
1730     * contain multiple tracks in it. One can find the total number of available tracks
1731     * using {@link #getTrackInfo()} to see what additional tracks become available
1732     * after this method call.
1733     *
1734     * @param fd the FileDescriptor for the file you want to play
1735     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1736     * @throws IllegalArgumentException if the mimeType is not supported.
1737     * @throws IllegalStateException if called in an invalid state.
1738     */
1739    public void addTimedTextSource(FileDescriptor fd, String mimeType)
1740            throws IllegalArgumentException, IllegalStateException {
1741        // intentionally less than LONG_MAX
1742        addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
1743    }
1744
1745    /**
1746     * Adds an external timed text file (FileDescriptor).
1747     *
1748     * It is the caller's responsibility to close the file descriptor.
1749     * It is safe to do so as soon as this call returns.
1750     *
1751     * Currently supported format is SubRip. Note that a single external timed text source may
1752     * contain multiple tracks in it. One can find the total number of available tracks
1753     * using {@link #getTrackInfo()} to see what additional tracks become available
1754     * after this method call.
1755     *
1756     * @param fd the FileDescriptor for the file you want to play
1757     * @param offset the offset into the file where the data to be played starts, in bytes
1758     * @param length the length in bytes of the data to be played
1759     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1760     * @throws IllegalArgumentException if the mimeType is not supported.
1761     * @throws IllegalStateException if called in an invalid state.
1762     */
1763    public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mimeType)
1764            throws IllegalArgumentException, IllegalStateException {
1765        if (!availableMimeTypeForExternalSource(mimeType)) {
1766            throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mimeType);
1767        }
1768
1769        Parcel request = Parcel.obtain();
1770        Parcel reply = Parcel.obtain();
1771        try {
1772            request.writeInterfaceToken(IMEDIA_PLAYER);
1773            request.writeInt(INVOKE_ID_ADD_EXTERNAL_SOURCE_FD);
1774            request.writeFileDescriptor(fd);
1775            request.writeLong(offset);
1776            request.writeLong(length);
1777            request.writeString(mimeType);
1778            invoke(request, reply);
1779        } finally {
1780            request.recycle();
1781            reply.recycle();
1782        }
1783    }
1784
1785    /**
1786     * Selects a track.
1787     * <p>
1788     * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
1789     * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
1790     * If a MediaPlayer is not in Started state, it just marks the track to be played.
1791     * </p>
1792     * <p>
1793     * In any valid state, if it is called multiple times on the same type of track (ie. Video,
1794     * Audio, Timed Text), the most recent one will be chosen.
1795     * </p>
1796     * <p>
1797     * The first audio and video tracks are selected by default if available, even though
1798     * this method is not called. However, no timed text track will be selected until
1799     * this function is called.
1800     * </p>
1801     * <p>
1802     * Currently, only timed text tracks or audio tracks can be selected via this method.
1803     * In addition, the support for selecting an audio track at runtime is pretty limited
1804     * in that an audio track can only be selected in the <em>Prepared</em> state.
1805     * </p>
1806     * @param index the index of the track to be selected. The valid range of the index
1807     * is 0..total number of track - 1. The total number of tracks as well as the type of
1808     * each individual track can be found by calling {@link #getTrackInfo()} method.
1809     * @throws IllegalStateException if called in an invalid state.
1810     *
1811     * @see android.media.MediaPlayer#getTrackInfo
1812     */
1813    public void selectTrack(int index) throws IllegalStateException {
1814        selectOrDeselectTrack(index, true /* select */);
1815    }
1816
1817    /**
1818     * Deselect a track.
1819     * <p>
1820     * Currently, the track must be a timed text track and no audio or video tracks can be
1821     * deselected. If the timed text track identified by index has not been
1822     * selected before, it throws an exception.
1823     * </p>
1824     * @param index the index of the track to be deselected. The valid range of the index
1825     * is 0..total number of tracks - 1. The total number of tracks as well as the type of
1826     * each individual track can be found by calling {@link #getTrackInfo()} method.
1827     * @throws IllegalStateException if called in an invalid state.
1828     *
1829     * @see android.media.MediaPlayer#getTrackInfo
1830     */
1831    public void deselectTrack(int index) throws IllegalStateException {
1832        selectOrDeselectTrack(index, false /* select */);
1833    }
1834
1835    private void selectOrDeselectTrack(int index, boolean select)
1836            throws IllegalStateException {
1837        Parcel request = Parcel.obtain();
1838        Parcel reply = Parcel.obtain();
1839        try {
1840            request.writeInterfaceToken(IMEDIA_PLAYER);
1841            request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
1842            request.writeInt(index);
1843            invoke(request, reply);
1844        } finally {
1845            request.recycle();
1846            reply.recycle();
1847        }
1848    }
1849
1850
1851    /**
1852     * @param reply Parcel with audio/video duration info for battery
1853                    tracking usage
1854     * @return The status code.
1855     * {@hide}
1856     */
1857    public native static int native_pullBatteryData(Parcel reply);
1858
1859    /**
1860     * Sets the target UDP re-transmit endpoint for the low level player.
1861     * Generally, the address portion of the endpoint is an IP multicast
1862     * address, although a unicast address would be equally valid.  When a valid
1863     * retransmit endpoint has been set, the media player will not decode and
1864     * render the media presentation locally.  Instead, the player will attempt
1865     * to re-multiplex its media data using the Android@Home RTP profile and
1866     * re-transmit to the target endpoint.  Receiver devices (which may be
1867     * either the same as the transmitting device or different devices) may
1868     * instantiate, prepare, and start a receiver player using a setDataSource
1869     * URL of the form...
1870     *
1871     * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
1872     *
1873     * to receive, decode and render the re-transmitted content.
1874     *
1875     * setRetransmitEndpoint may only be called before setDataSource has been
1876     * called; while the player is in the Idle state.
1877     *
1878     * @param endpoint the address and UDP port of the re-transmission target or
1879     * null if no re-transmission is to be performed.
1880     * @throws IllegalStateException if it is called in an invalid state
1881     * @throws IllegalArgumentException if the retransmit endpoint is supplied,
1882     * but invalid.
1883     *
1884     * {@hide} pending API council
1885     */
1886    public void setRetransmitEndpoint(InetSocketAddress endpoint)
1887            throws IllegalStateException, IllegalArgumentException
1888    {
1889        String addrString = null;
1890        int port = 0;
1891
1892        if (null != endpoint) {
1893            addrString = endpoint.getAddress().getHostAddress();
1894            port = endpoint.getPort();
1895        }
1896
1897        int ret = native_setRetransmitEndpoint(addrString, port);
1898        if (ret != 0) {
1899            throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
1900        }
1901    }
1902
1903    private native final int native_setRetransmitEndpoint(String addrString, int port);
1904
1905    @Override
1906    protected void finalize() { native_finalize(); }
1907
1908    /* Do not change these values without updating their counterparts
1909     * in include/media/mediaplayer.h!
1910     */
1911    private static final int MEDIA_NOP = 0; // interface test message
1912    private static final int MEDIA_PREPARED = 1;
1913    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
1914    private static final int MEDIA_BUFFERING_UPDATE = 3;
1915    private static final int MEDIA_SEEK_COMPLETE = 4;
1916    private static final int MEDIA_SET_VIDEO_SIZE = 5;
1917    private static final int MEDIA_TIMED_TEXT = 99;
1918    private static final int MEDIA_ERROR = 100;
1919    private static final int MEDIA_INFO = 200;
1920    private static final int MEDIA_SUBTITLE_DATA = 201;
1921
1922    private class EventHandler extends Handler
1923    {
1924        private MediaPlayer mMediaPlayer;
1925
1926        public EventHandler(MediaPlayer mp, Looper looper) {
1927            super(looper);
1928            mMediaPlayer = mp;
1929        }
1930
1931        @Override
1932        public void handleMessage(Message msg) {
1933            if (mMediaPlayer.mNativeContext == 0) {
1934                Log.w(TAG, "mediaplayer went away with unhandled events");
1935                return;
1936            }
1937            switch(msg.what) {
1938            case MEDIA_PREPARED:
1939                if (mOnPreparedListener != null)
1940                    mOnPreparedListener.onPrepared(mMediaPlayer);
1941                return;
1942
1943            case MEDIA_PLAYBACK_COMPLETE:
1944                if (mOnCompletionListener != null)
1945                    mOnCompletionListener.onCompletion(mMediaPlayer);
1946                stayAwake(false);
1947                return;
1948
1949            case MEDIA_BUFFERING_UPDATE:
1950                if (mOnBufferingUpdateListener != null)
1951                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
1952                return;
1953
1954            case MEDIA_SEEK_COMPLETE:
1955              if (mOnSeekCompleteListener != null)
1956                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
1957              return;
1958
1959            case MEDIA_SET_VIDEO_SIZE:
1960              if (mOnVideoSizeChangedListener != null)
1961                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
1962              return;
1963
1964            case MEDIA_ERROR:
1965                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
1966                boolean error_was_handled = false;
1967                if (mOnErrorListener != null) {
1968                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
1969                }
1970                if (mOnCompletionListener != null && ! error_was_handled) {
1971                    mOnCompletionListener.onCompletion(mMediaPlayer);
1972                }
1973                stayAwake(false);
1974                return;
1975
1976            case MEDIA_INFO:
1977                if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
1978                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
1979                }
1980                if (mOnInfoListener != null) {
1981                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
1982                }
1983                // No real default action so far.
1984                return;
1985            case MEDIA_TIMED_TEXT:
1986                if (mOnTimedTextListener == null)
1987                    return;
1988                if (msg.obj == null) {
1989                    mOnTimedTextListener.onTimedText(mMediaPlayer, null);
1990                } else {
1991                    if (msg.obj instanceof Parcel) {
1992                        Parcel parcel = (Parcel)msg.obj;
1993                        TimedText text = new TimedText(parcel);
1994                        parcel.recycle();
1995                        mOnTimedTextListener.onTimedText(mMediaPlayer, text);
1996                    }
1997                }
1998                return;
1999
2000            case MEDIA_SUBTITLE_DATA:
2001                if (mOnSubtitleDataListener == null) {
2002                    return;
2003                }
2004                if (msg.obj instanceof Parcel) {
2005                    Parcel parcel = (Parcel) msg.obj;
2006                    SubtitleData data = new SubtitleData(parcel);
2007                    parcel.recycle();
2008                    mOnSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
2009                }
2010                return;
2011
2012            case MEDIA_NOP: // interface test message - ignore
2013                break;
2014
2015            default:
2016                Log.e(TAG, "Unknown message type " + msg.what);
2017                return;
2018            }
2019        }
2020    }
2021
2022    /*
2023     * Called from native code when an interesting event happens.  This method
2024     * just uses the EventHandler system to post the event back to the main app thread.
2025     * We use a weak reference to the original MediaPlayer object so that the native
2026     * code is safe from the object disappearing from underneath it.  (This is
2027     * the cookie passed to native_setup().)
2028     */
2029    private static void postEventFromNative(Object mediaplayer_ref,
2030                                            int what, int arg1, int arg2, Object obj)
2031    {
2032        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
2033        if (mp == null) {
2034            return;
2035        }
2036
2037        if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
2038            // this acquires the wakelock if needed, and sets the client side state
2039            mp.start();
2040        }
2041        if (mp.mEventHandler != null) {
2042            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
2043            mp.mEventHandler.sendMessage(m);
2044        }
2045    }
2046
2047    /**
2048     * Interface definition for a callback to be invoked when the media
2049     * source is ready for playback.
2050     */
2051    public interface OnPreparedListener
2052    {
2053        /**
2054         * Called when the media file is ready for playback.
2055         *
2056         * @param mp the MediaPlayer that is ready for playback
2057         */
2058        void onPrepared(MediaPlayer mp);
2059    }
2060
2061    /**
2062     * Register a callback to be invoked when the media source is ready
2063     * for playback.
2064     *
2065     * @param listener the callback that will be run
2066     */
2067    public void setOnPreparedListener(OnPreparedListener listener)
2068    {
2069        mOnPreparedListener = listener;
2070    }
2071
2072    private OnPreparedListener mOnPreparedListener;
2073
2074    /**
2075     * Interface definition for a callback to be invoked when playback of
2076     * a media source has completed.
2077     */
2078    public interface OnCompletionListener
2079    {
2080        /**
2081         * Called when the end of a media source is reached during playback.
2082         *
2083         * @param mp the MediaPlayer that reached the end of the file
2084         */
2085        void onCompletion(MediaPlayer mp);
2086    }
2087
2088    /**
2089     * Register a callback to be invoked when the end of a media source
2090     * has been reached during playback.
2091     *
2092     * @param listener the callback that will be run
2093     */
2094    public void setOnCompletionListener(OnCompletionListener listener)
2095    {
2096        mOnCompletionListener = listener;
2097    }
2098
2099    private OnCompletionListener mOnCompletionListener;
2100
2101    /**
2102     * Interface definition of a callback to be invoked indicating buffering
2103     * status of a media resource being streamed over the network.
2104     */
2105    public interface OnBufferingUpdateListener
2106    {
2107        /**
2108         * Called to update status in buffering a media stream received through
2109         * progressive HTTP download. The received buffering percentage
2110         * indicates how much of the content has been buffered or played.
2111         * For example a buffering update of 80 percent when half the content
2112         * has already been played indicates that the next 30 percent of the
2113         * content to play has been buffered.
2114         *
2115         * @param mp      the MediaPlayer the update pertains to
2116         * @param percent the percentage (0-100) of the content
2117         *                that has been buffered or played thus far
2118         */
2119        void onBufferingUpdate(MediaPlayer mp, int percent);
2120    }
2121
2122    /**
2123     * Register a callback to be invoked when the status of a network
2124     * stream's buffer has changed.
2125     *
2126     * @param listener the callback that will be run.
2127     */
2128    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
2129    {
2130        mOnBufferingUpdateListener = listener;
2131    }
2132
2133    private OnBufferingUpdateListener mOnBufferingUpdateListener;
2134
2135    /**
2136     * Interface definition of a callback to be invoked indicating
2137     * the completion of a seek operation.
2138     */
2139    public interface OnSeekCompleteListener
2140    {
2141        /**
2142         * Called to indicate the completion of a seek operation.
2143         *
2144         * @param mp the MediaPlayer that issued the seek operation
2145         */
2146        public void onSeekComplete(MediaPlayer mp);
2147    }
2148
2149    /**
2150     * Register a callback to be invoked when a seek operation has been
2151     * completed.
2152     *
2153     * @param listener the callback that will be run
2154     */
2155    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
2156    {
2157        mOnSeekCompleteListener = listener;
2158    }
2159
2160    private OnSeekCompleteListener mOnSeekCompleteListener;
2161
2162    /**
2163     * Interface definition of a callback to be invoked when the
2164     * video size is first known or updated
2165     */
2166    public interface OnVideoSizeChangedListener
2167    {
2168        /**
2169         * Called to indicate the video size
2170         *
2171         * The video size (width and height) could be 0 if there was no video,
2172         * no display surface was set, or the value was not determined yet.
2173         *
2174         * @param mp        the MediaPlayer associated with this callback
2175         * @param width     the width of the video
2176         * @param height    the height of the video
2177         */
2178        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
2179    }
2180
2181    /**
2182     * Register a callback to be invoked when the video size is
2183     * known or updated.
2184     *
2185     * @param listener the callback that will be run
2186     */
2187    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
2188    {
2189        mOnVideoSizeChangedListener = listener;
2190    }
2191
2192    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
2193
2194    /**
2195     * Interface definition of a callback to be invoked when a
2196     * timed text is available for display.
2197     */
2198    public interface OnTimedTextListener
2199    {
2200        /**
2201         * Called to indicate an avaliable timed text
2202         *
2203         * @param mp             the MediaPlayer associated with this callback
2204         * @param text           the timed text sample which contains the text
2205         *                       needed to be displayed and the display format.
2206         */
2207        public void onTimedText(MediaPlayer mp, TimedText text);
2208    }
2209
2210    /**
2211     * Register a callback to be invoked when a timed text is available
2212     * for display.
2213     *
2214     * @param listener the callback that will be run
2215     */
2216    public void setOnTimedTextListener(OnTimedTextListener listener)
2217    {
2218        mOnTimedTextListener = listener;
2219    }
2220
2221    private OnTimedTextListener mOnTimedTextListener;
2222
2223    /**
2224     * Interface definition of a callback to be invoked when a
2225     * track has data available.
2226     *
2227     * @hide
2228     */
2229    public interface OnSubtitleDataListener
2230    {
2231        public void onSubtitleData(MediaPlayer mp, SubtitleData data);
2232    }
2233
2234    /**
2235     * Register a callback to be invoked when a track has data available.
2236     *
2237     * @param listener the callback that will be run
2238     *
2239     * @hide
2240     */
2241    public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
2242    {
2243        mOnSubtitleDataListener = listener;
2244    }
2245
2246    private OnSubtitleDataListener mOnSubtitleDataListener;
2247
2248    /* Do not change these values without updating their counterparts
2249     * in include/media/mediaplayer.h!
2250     */
2251    /** Unspecified media player error.
2252     * @see android.media.MediaPlayer.OnErrorListener
2253     */
2254    public static final int MEDIA_ERROR_UNKNOWN = 1;
2255
2256    /** Media server died. In this case, the application must release the
2257     * MediaPlayer object and instantiate a new one.
2258     * @see android.media.MediaPlayer.OnErrorListener
2259     */
2260    public static final int MEDIA_ERROR_SERVER_DIED = 100;
2261
2262    /** The video is streamed and its container is not valid for progressive
2263     * playback i.e the video's index (e.g moov atom) is not at the start of the
2264     * file.
2265     * @see android.media.MediaPlayer.OnErrorListener
2266     */
2267    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
2268
2269    /** File or network related operation errors. */
2270    public static final int MEDIA_ERROR_IO = -1004;
2271    /** Bitstream is not conforming to the related coding standard or file spec. */
2272    public static final int MEDIA_ERROR_MALFORMED = -1007;
2273    /** Bitstream is conforming to the related coding standard or file spec, but
2274     * the media framework does not support the feature. */
2275    public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
2276    /** Some operation takes too long to complete, usually more than 3-5 seconds. */
2277    public static final int MEDIA_ERROR_TIMED_OUT = -110;
2278
2279    /**
2280     * Interface definition of a callback to be invoked when there
2281     * has been an error during an asynchronous operation (other errors
2282     * will throw exceptions at method call time).
2283     */
2284    public interface OnErrorListener
2285    {
2286        /**
2287         * Called to indicate an error.
2288         *
2289         * @param mp      the MediaPlayer the error pertains to
2290         * @param what    the type of error that has occurred:
2291         * <ul>
2292         * <li>{@link #MEDIA_ERROR_UNKNOWN}
2293         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
2294         * </ul>
2295         * @param extra an extra code, specific to the error. Typically
2296         * implementation dependent.
2297         * <ul>
2298         * <li>{@link #MEDIA_ERROR_IO}
2299         * <li>{@link #MEDIA_ERROR_MALFORMED}
2300         * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
2301         * <li>{@link #MEDIA_ERROR_TIMED_OUT}
2302         * </ul>
2303         * @return True if the method handled the error, false if it didn't.
2304         * Returning false, or not having an OnErrorListener at all, will
2305         * cause the OnCompletionListener to be called.
2306         */
2307        boolean onError(MediaPlayer mp, int what, int extra);
2308    }
2309
2310    /**
2311     * Register a callback to be invoked when an error has happened
2312     * during an asynchronous operation.
2313     *
2314     * @param listener the callback that will be run
2315     */
2316    public void setOnErrorListener(OnErrorListener listener)
2317    {
2318        mOnErrorListener = listener;
2319    }
2320
2321    private OnErrorListener mOnErrorListener;
2322
2323
2324    /* Do not change these values without updating their counterparts
2325     * in include/media/mediaplayer.h!
2326     */
2327    /** Unspecified media player info.
2328     * @see android.media.MediaPlayer.OnInfoListener
2329     */
2330    public static final int MEDIA_INFO_UNKNOWN = 1;
2331
2332    /** The player was started because it was used as the next player for another
2333     * player, which just completed playback.
2334     * @see android.media.MediaPlayer.OnInfoListener
2335     * @hide
2336     */
2337    public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
2338
2339    /** The player just pushed the very first video frame for rendering.
2340     * @see android.media.MediaPlayer.OnInfoListener
2341     */
2342    public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
2343
2344    /** The video is too complex for the decoder: it can't decode frames fast
2345     *  enough. Possibly only the audio plays fine at this stage.
2346     * @see android.media.MediaPlayer.OnInfoListener
2347     */
2348    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
2349
2350    /** MediaPlayer is temporarily pausing playback internally in order to
2351     * buffer more data.
2352     * @see android.media.MediaPlayer.OnInfoListener
2353     */
2354    public static final int MEDIA_INFO_BUFFERING_START = 701;
2355
2356    /** MediaPlayer is resuming playback after filling buffers.
2357     * @see android.media.MediaPlayer.OnInfoListener
2358     */
2359    public static final int MEDIA_INFO_BUFFERING_END = 702;
2360
2361    /** Bad interleaving means that a media has been improperly interleaved or
2362     * not interleaved at all, e.g has all the video samples first then all the
2363     * audio ones. Video is playing but a lot of disk seeks may be happening.
2364     * @see android.media.MediaPlayer.OnInfoListener
2365     */
2366    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
2367
2368    /** The media cannot be seeked (e.g live stream)
2369     * @see android.media.MediaPlayer.OnInfoListener
2370     */
2371    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
2372
2373    /** A new set of metadata is available.
2374     * @see android.media.MediaPlayer.OnInfoListener
2375     */
2376    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
2377
2378    /** Failed to handle timed text track properly.
2379     * @see android.media.MediaPlayer.OnInfoListener
2380     *
2381     * {@hide}
2382     */
2383    public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
2384
2385    /**
2386     * Interface definition of a callback to be invoked to communicate some
2387     * info and/or warning about the media or its playback.
2388     */
2389    public interface OnInfoListener
2390    {
2391        /**
2392         * Called to indicate an info or a warning.
2393         *
2394         * @param mp      the MediaPlayer the info pertains to.
2395         * @param what    the type of info or warning.
2396         * <ul>
2397         * <li>{@link #MEDIA_INFO_UNKNOWN}
2398         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
2399         * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
2400         * <li>{@link #MEDIA_INFO_BUFFERING_START}
2401         * <li>{@link #MEDIA_INFO_BUFFERING_END}
2402         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
2403         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
2404         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
2405         * </ul>
2406         * @param extra an extra code, specific to the info. Typically
2407         * implementation dependent.
2408         * @return True if the method handled the info, false if it didn't.
2409         * Returning false, or not having an OnErrorListener at all, will
2410         * cause the info to be discarded.
2411         */
2412        boolean onInfo(MediaPlayer mp, int what, int extra);
2413    }
2414
2415    /**
2416     * Register a callback to be invoked when an info/warning is available.
2417     *
2418     * @param listener the callback that will be run
2419     */
2420    public void setOnInfoListener(OnInfoListener listener)
2421    {
2422        mOnInfoListener = listener;
2423    }
2424
2425    private OnInfoListener mOnInfoListener;
2426
2427    /*
2428     * Test whether a given video scaling mode is supported.
2429     */
2430    private boolean isVideoScalingModeSupported(int mode) {
2431        return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
2432                mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
2433    }
2434
2435    private Context mProxyContext = null;
2436    private ProxyReceiver mProxyReceiver = null;
2437
2438    private void setupProxyListener(Context context) {
2439        IntentFilter filter = new IntentFilter();
2440        filter.addAction(Proxy.PROXY_CHANGE_ACTION);
2441        mProxyReceiver = new ProxyReceiver();
2442        mProxyContext = context;
2443
2444        Intent currentProxy =
2445            context.getApplicationContext().registerReceiver(mProxyReceiver, filter);
2446
2447        if (currentProxy != null) {
2448            handleProxyBroadcast(currentProxy);
2449        }
2450    }
2451
2452    private void disableProxyListener() {
2453        if (mProxyReceiver == null) {
2454            return;
2455        }
2456
2457        Context appContext = mProxyContext.getApplicationContext();
2458        if (appContext != null) {
2459            appContext.unregisterReceiver(mProxyReceiver);
2460        }
2461
2462        mProxyReceiver = null;
2463        mProxyContext = null;
2464    }
2465
2466    private void handleProxyBroadcast(Intent intent) {
2467        ProxyProperties props =
2468            (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
2469
2470        if (props == null || props.getHost() == null) {
2471            updateProxyConfig(null);
2472        } else {
2473            updateProxyConfig(props);
2474        }
2475    }
2476
2477    private class ProxyReceiver extends BroadcastReceiver {
2478        @Override
2479        public void onReceive(Context context, Intent intent) {
2480            if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
2481                handleProxyBroadcast(intent);
2482            }
2483        }
2484    }
2485
2486    private native void updateProxyConfig(ProxyProperties props);
2487}
2488