blob: 210d08f7c210dbe7ebe913fd9941a89a0a25ba4a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Wei Jiad93fcf42015-02-09 16:05:53 -080019import android.annotation.IntDef;
John Spurlock1af30c72014-03-10 08:33:35 -040020import android.app.ActivityThread;
21import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.ContentResolver;
23import android.content.Context;
24import android.content.res.AssetFileDescriptor;
25import android.net.Uri;
26import android.os.Handler;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070027import android.os.HandlerThread;
Andreas Huberd2506a52014-01-29 10:32:46 -080028import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.os.Looper;
30import android.os.Message;
Nicolas Catania20cb94e2009-05-12 23:25:55 -070031import android.os.Parcel;
Insun Kang41f3f712012-02-16 20:28:27 +090032import android.os.Parcelable;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070033import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.PowerManager;
John Spurlock1af30c72014-03-10 08:33:35 -040035import android.os.RemoteException;
36import android.os.ServiceManager;
Jeff Sharkey3b566b82014-11-12 10:39:56 -080037import android.provider.Settings;
Robert Shih3cdf7c52014-07-23 17:18:46 -070038import android.system.ErrnoException;
39import android.system.OsConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.util.Log;
41import android.view.Surface;
42import android.view.SurfaceHolder;
Glenn Kastencc562a32011-02-08 17:26:17 -080043import android.graphics.SurfaceTexture;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.media.AudioManager;
Lajos Molnar1c56a672013-08-15 12:05:52 -070045import android.media.MediaFormat;
Lajos Molnar3d998562013-08-15 17:05:05 -070046import android.media.MediaTimeProvider;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070047import android.media.SubtitleController;
Robert Shih3cdf7c52014-07-23 17:18:46 -070048import android.media.SubtitleController.Anchor;
Chong Zhang83ddaf62013-08-06 09:43:22 -070049import android.media.SubtitleData;
Robert Shih3cdf7c52014-07-23 17:18:46 -070050import android.media.SubtitleTrack.RenderingWidget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
John Spurlock1af30c72014-03-10 08:33:35 -040052import com.android.internal.app.IAppOpsService;
53
Robert Shih3cdf7c52014-07-23 17:18:46 -070054import libcore.io.IoBridge;
55import libcore.io.Libcore;
56
57import java.io.ByteArrayOutputStream;
James Donge00b6f32012-04-11 21:18:43 -070058import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.io.FileDescriptor;
James Donge00b6f32012-04-11 21:18:43 -070060import java.io.FileInputStream;
Jeff Sharkey87d76f62014-12-09 15:27:19 -080061import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.io.IOException;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070063import java.io.InputStream;
64import java.lang.Runnable;
Wei Jiad93fcf42015-02-09 16:05:53 -080065import java.lang.annotation.Retention;
66import java.lang.annotation.RetentionPolicy;
John Grossman720aa282012-02-22 15:38:35 -080067import java.net.InetSocketAddress;
Andreas Huber25643002010-01-28 11:19:57 -080068import java.util.Map;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070069import java.util.Scanner;
Nicolas Catania9193e082009-07-06 12:43:36 -070070import java.util.Set;
Lajos Molnar3d998562013-08-15 17:05:05 -070071import java.util.Vector;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.lang.ref.WeakReference;
73
74/**
75 * MediaPlayer class can be used to control playback
76 * of audio/video files and streams. An example on how to use the methods in
77 * this class can be found in {@link android.widget.VideoView}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 *
79 * <p>Topics covered here are:
80 * <ol>
81 * <li><a href="#StateDiagram">State Diagram</a>
82 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
83 * <li><a href="#Permissions">Permissions</a>
James Dong9ddb7882011-06-14 14:01:57 -070084 * <li><a href="#Callbacks">Register informational and error callbacks</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * </ol>
86 *
Joe Fernandez61fd1e82011-10-26 13:39:11 -070087 * <div class="special reference">
88 * <h3>Developer Guides</h3>
89 * <p>For more information about how to use MediaPlayer, read the
90 * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
91 * </div>
92 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 * <a name="StateDiagram"></a>
94 * <h3>State Diagram</h3>
95 *
96 * <p>Playback control of audio/video files and streams is managed as a state
97 * machine. The following diagram shows the life cycle and the states of a
98 * MediaPlayer object driven by the supported playback control operations.
99 * The ovals represent the states a MediaPlayer object may reside
100 * in. The arcs represent the playback control operations that drive the object
Nicolas Catania32f82772009-06-11 16:33:49 -0700101 * state transition. There are two types of arcs. The arcs with a single arrow
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 * head represent synchronous method calls, while those with
103 * a double arrow head represent asynchronous method calls.</p>
104 *
105 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
106 * alt="MediaPlayer State diagram"
107 * border="0" /></p>
108 *
109 * <p>From this state diagram, one can see that a MediaPlayer object has the
110 * following states:</p>
111 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700112 * <li>When a MediaPlayer object is just created using <code>new</code> or
113 * after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
114 * {@link #release()} is called, it is in the <em>End</em> state. Between these
115 * two states is the life cycle of the MediaPlayer object.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700117 * <li>There is a subtle but important difference between a newly constructed
118 * MediaPlayer object and the MediaPlayer object after {@link #reset()}
119 * is called. It is a programming error to invoke methods such
120 * as {@link #getCurrentPosition()},
121 * {@link #getDuration()}, {@link #getVideoHeight()},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 * {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
123 * {@link #setLooping(boolean)},
Nicolas Catania32f82772009-06-11 16:33:49 -0700124 * {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
125 * {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
126 * {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
127 * methods is called right after a MediaPlayer object is constructed,
128 * the user supplied callback method OnErrorListener.onError() won't be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 * called by the internal player engine and the object state remains
Nicolas Catania32f82772009-06-11 16:33:49 -0700130 * unchanged; but if these methods are called right after {@link #reset()},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 * the user supplied callback method OnErrorListener.onError() will be
Nicolas Catania32f82772009-06-11 16:33:49 -0700132 * invoked by the internal player engine and the object will be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 * transfered to the <em>Error</em> state. </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700134 * <li>It is also recommended that once
135 * a MediaPlayer object is no longer being used, call {@link #release()} immediately
136 * so that resources used by the internal player engine associated with the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 * MediaPlayer object can be released immediately. Resource may include
Nicolas Catania32f82772009-06-11 16:33:49 -0700138 * singleton resources such as hardware acceleration components and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 * failure to call {@link #release()} may cause subsequent instances of
140 * MediaPlayer objects to fallback to software implementations or fail
141 * altogether. Once the MediaPlayer
Nicolas Catania32f82772009-06-11 16:33:49 -0700142 * object is in the <em>End</em> state, it can no longer be used and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 * there is no way to bring it back to any other state. </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700144 * <li>Furthermore,
145 * the MediaPlayer objects created using <code>new</code> is in the
146 * <em>Idle</em> state, while those created with one
147 * of the overloaded convenient <code>create</code> methods are <em>NOT</em>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 * in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
149 * state if the creation using <code>create</code> method is successful.
150 * </li>
151 * </ul>
152 * </li>
153 * <li>In general, some playback control operation may fail due to various
154 * reasons, such as unsupported audio/video format, poorly interleaved
155 * audio/video, resolution too high, streaming timeout, and the like.
156 * Thus, error reporting and recovery is an important concern under
Nicolas Catania32f82772009-06-11 16:33:49 -0700157 * these circumstances. Sometimes, due to programming errors, invoking a playback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 * control operation in an invalid state may also occur. Under all these
159 * error conditions, the internal player engine invokes a user supplied
160 * OnErrorListener.onError() method if an OnErrorListener has been
161 * registered beforehand via
162 * {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
163 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700164 * <li>It is important to note that once an error occurs, the
165 * MediaPlayer object enters the <em>Error</em> state (except as noted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 * above), even if an error listener has not been registered by the application.</li>
167 * <li>In order to reuse a MediaPlayer object that is in the <em>
Nicolas Catania32f82772009-06-11 16:33:49 -0700168 * Error</em> state and recover from the error,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 * {@link #reset()} can be called to restore the object to its <em>Idle</em>
170 * state.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700171 * <li>It is good programming practice to have your application
172 * register a OnErrorListener to look out for error notifications from
173 * the internal player engine.</li>
hugh kennedyc6f8ea42010-04-28 15:04:10 -0400174 * <li>IllegalStateException is
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 * thrown to prevent programming errors such as calling {@link #prepare()},
176 * {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
177 * </code> methods in an invalid state. </li>
178 * </ul>
179 * </li>
180 * <li>Calling
181 * {@link #setDataSource(FileDescriptor)}, or
182 * {@link #setDataSource(String)}, or
183 * {@link #setDataSource(Context, Uri)}, or
Chris Watkins4eaa2932015-03-20 10:31:42 -0700184 * {@link #setDataSource(FileDescriptor, long, long)}, or
185 * {@link #setDataSource(MediaDataSource)} transfers a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 * MediaPlayer object in the <em>Idle</em> state to the
187 * <em>Initialized</em> state.
188 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700189 * <li>An IllegalStateException is thrown if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 * setDataSource() is called in any other state.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700191 * <li>It is good programming
192 * practice to always look out for <code>IllegalArgumentException</code>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 * and <code>IOException</code> that may be thrown from the overloaded
194 * <code>setDataSource</code> methods.</li>
195 * </ul>
196 * </li>
197 * <li>A MediaPlayer object must first enter the <em>Prepared</em> state
Nicolas Catania32f82772009-06-11 16:33:49 -0700198 * before playback can be started.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 * <ul>
200 * <li>There are two ways (synchronous vs.
201 * asynchronous) that the <em>Prepared</em> state can be reached:
202 * either a call to {@link #prepare()} (synchronous) which
203 * transfers the object to the <em>Prepared</em> state once the method call
204 * returns, or a call to {@link #prepareAsync()} (asynchronous) which
Nicolas Catania32f82772009-06-11 16:33:49 -0700205 * first transfers the object to the <em>Preparing</em> state after the
206 * call returns (which occurs almost right way) while the internal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 * player engine continues working on the rest of preparation work
208 * until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
209 * the internal player engine then calls a user supplied callback method,
210 * onPrepared() of the OnPreparedListener interface, if an
211 * OnPreparedListener is registered beforehand via {@link
212 * #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
213 * <li>It is important to note that
214 * the <em>Preparing</em> state is a transient state, and the behavior
215 * of calling any method with side effect while a MediaPlayer object is
216 * in the <em>Preparing</em> state is undefined.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700217 * <li>An IllegalStateException is
218 * thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
219 * any other state.</li>
220 * <li>While in the <em>Prepared</em> state, properties
221 * such as audio/sound volume, screenOnWhilePlaying, looping can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 * adjusted by invoking the corresponding set methods.</li>
223 * </ul>
224 * </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700225 * <li>To start the playback, {@link #start()} must be called. After
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 * {@link #start()} returns successfully, the MediaPlayer object is in the
Nicolas Catania32f82772009-06-11 16:33:49 -0700227 * <em>Started</em> state. {@link #isPlaying()} can be called to test
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 * whether the MediaPlayer object is in the <em>Started</em> state.
229 * <ul>
230 * <li>While in the <em>Started</em> state, the internal player engine calls
231 * a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
Nicolas Catania32f82772009-06-11 16:33:49 -0700232 * method if a OnBufferingUpdateListener has been registered beforehand
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 * via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
234 * This callback allows applications to keep track of the buffering status
235 * while streaming audio/video.</li>
236 * <li>Calling {@link #start()} has not effect
237 * on a MediaPlayer object that is already in the <em>Started</em> state.</li>
238 * </ul>
239 * </li>
240 * <li>Playback can be paused and stopped, and the current playback position
Nicolas Catania32f82772009-06-11 16:33:49 -0700241 * can be adjusted. Playback can be paused via {@link #pause()}. When the call to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 * {@link #pause()} returns, the MediaPlayer object enters the
Nicolas Catania32f82772009-06-11 16:33:49 -0700243 * <em>Paused</em> state. Note that the transition from the <em>Started</em>
244 * state to the <em>Paused</em> state and vice versa happens
245 * asynchronously in the player engine. It may take some time before
246 * the state is updated in calls to {@link #isPlaying()}, and it can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 * a number of seconds in the case of streamed content.
248 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700249 * <li>Calling {@link #start()} to resume playback for a paused
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 * MediaPlayer object, and the resumed playback
Nicolas Catania32f82772009-06-11 16:33:49 -0700251 * position is the same as where it was paused. When the call to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 * {@link #start()} returns, the paused MediaPlayer object goes back to
253 * the <em>Started</em> state.</li>
254 * <li>Calling {@link #pause()} has no effect on
255 * a MediaPlayer object that is already in the <em>Paused</em> state.</li>
256 * </ul>
257 * </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700258 * <li>Calling {@link #stop()} stops playback and causes a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 * MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
Nicolas Catania32f82772009-06-11 16:33:49 -0700260 * </em> or <em>PlaybackCompleted</em> state to enter the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 * <em>Stopped</em> state.
262 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700263 * <li>Once in the <em>Stopped</em> state, playback cannot be started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 * until {@link #prepare()} or {@link #prepareAsync()} are called to set
265 * the MediaPlayer object to the <em>Prepared</em> state again.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700266 * <li>Calling {@link #stop()} has no effect on a MediaPlayer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 * object that is already in the <em>Stopped</em> state.</li>
268 * </ul>
269 * </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700270 * <li>The playback position can be adjusted with a call to
271 * {@link #seekTo(int)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 * <ul>
273 * <li>Although the asynchronuous {@link #seekTo(int)}
274 * call returns right way, the actual seek operation may take a while to
Nicolas Catania32f82772009-06-11 16:33:49 -0700275 * finish, especially for audio/video being streamed. When the actual
276 * seek operation completes, the internal player engine calls a user
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 * supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
Nicolas Catania32f82772009-06-11 16:33:49 -0700278 * has been registered beforehand via
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
280 * <li>Please
281 * note that {@link #seekTo(int)} can also be called in the other states,
282 * such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
283 * </em> state.</li>
284 * <li>Furthermore, the actual current playback position
285 * can be retrieved with a call to {@link #getCurrentPosition()}, which
Nicolas Catania32f82772009-06-11 16:33:49 -0700286 * is helpful for applications such as a Music player that need to keep
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 * track of the playback progress.</li>
288 * </ul>
289 * </li>
290 * <li>When the playback reaches the end of stream, the playback completes.
291 * <ul>
292 * <li>If the looping mode was being set to <var>true</var>with
293 * {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
294 * the <em>Started</em> state.</li>
295 * <li>If the looping mode was set to <var>false
296 * </var>, the player engine calls a user supplied callback method,
297 * OnCompletion.onCompletion(), if a OnCompletionListener is registered
298 * beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
299 * The invoke of the callback signals that the object is now in the <em>
300 * PlaybackCompleted</em> state.</li>
301 * <li>While in the <em>PlaybackCompleted</em>
302 * state, calling {@link #start()} can restart the playback from the
303 * beginning of the audio/video source.</li>
304 * </ul>
305 *
306 *
307 * <a name="Valid_and_Invalid_States"></a>
308 * <h3>Valid and invalid states</h3>
309 *
310 * <table border="0" cellspacing="0" cellpadding="0">
311 * <tr><td>Method Name </p></td>
312 * <td>Valid Sates </p></td>
313 * <td>Invalid States </p></td>
314 * <td>Comments </p></td></tr>
Eric Laurent17cb2802010-08-03 03:50:02 -0700315 * <tr><td>attachAuxEffect </p></td>
316 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
317 * <td>{Idle, Error} </p></td>
318 * <td>This method must be called after setDataSource.
319 * Calling it does not change the object state. </p></td></tr>
320 * <tr><td>getAudioSessionId </p></td>
321 * <td>any </p></td>
322 * <td>{} </p></td>
323 * <td>This method can be called in any state and calling it does not change
324 * the object state. </p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 * <tr><td>getCurrentPosition </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700326 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * PlaybackCompleted} </p></td>
328 * <td>{Error}</p></td>
329 * <td>Successful invoke of this method in a valid state does not change the
330 * state. Calling this method in an invalid state transfers the object
331 * to the <em>Error</em> state. </p></td></tr>
332 * <tr><td>getDuration </p></td>
333 * <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
334 * <td>{Idle, Initialized, Error} </p></td>
335 * <td>Successful invoke of this method in a valid state does not change the
Nicolas Catania32f82772009-06-11 16:33:49 -0700336 * state. Calling this method in an invalid state transfers the object
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 * to the <em>Error</em> state. </p></td></tr>
338 * <tr><td>getVideoHeight </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700339 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 * PlaybackCompleted}</p></td>
341 * <td>{Error}</p></td>
342 * <td>Successful invoke of this method in a valid state does not change the
Nicolas Catania32f82772009-06-11 16:33:49 -0700343 * state. Calling this method in an invalid state transfers the object
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 * to the <em>Error</em> state. </p></td></tr>
345 * <tr><td>getVideoWidth </p></td>
346 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
347 * PlaybackCompleted}</p></td>
348 * <td>{Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700349 * <td>Successful invoke of this method in a valid state does not change
350 * the state. Calling this method in an invalid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 * object to the <em>Error</em> state. </p></td></tr>
352 * <tr><td>isPlaying </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700353 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 * PlaybackCompleted}</p></td>
355 * <td>{Error}</p></td>
356 * <td>Successful invoke of this method in a valid state does not change
Nicolas Catania32f82772009-06-11 16:33:49 -0700357 * the state. Calling this method in an invalid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 * object to the <em>Error</em> state. </p></td></tr>
359 * <tr><td>pause </p></td>
kmccormickb04c07f2013-03-29 15:48:45 -0700360 * <td>{Started, Paused, PlaybackCompleted}</p></td>
361 * <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700362 * <td>Successful invoke of this method in a valid state transfers the
363 * object to the <em>Paused</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
365 * <tr><td>prepare </p></td>
366 * <td>{Initialized, Stopped} </p></td>
367 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700368 * <td>Successful invoke of this method in a valid state transfers the
369 * object to the <em>Prepared</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 * invalid state throws an IllegalStateException.</p></td></tr>
371 * <tr><td>prepareAsync </p></td>
372 * <td>{Initialized, Stopped} </p></td>
373 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700374 * <td>Successful invoke of this method in a valid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 * object to the <em>Preparing</em> state. Calling this method in an
376 * invalid state throws an IllegalStateException.</p></td></tr>
377 * <tr><td>release </p></td>
378 * <td>any </p></td>
379 * <td>{} </p></td>
380 * <td>After {@link #release()}, the object is no longer available. </p></td></tr>
381 * <tr><td>reset </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700382 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 * PlaybackCompleted, Error}</p></td>
384 * <td>{}</p></td>
385 * <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
386 * <tr><td>seekTo </p></td>
387 * <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
388 * <td>{Idle, Initialized, Stopped, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700389 * <td>Successful invoke of this method in a valid state does not change
390 * the state. Calling this method in an invalid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 * object to the <em>Error</em> state. </p></td></tr>
Jean-Michel Trivi79f5cd12014-07-15 15:42:25 -0700392 * <tr><td>setAudioAttributes </p></td>
393 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
394 * PlaybackCompleted}</p></td>
395 * <td>{Error}</p></td>
396 * <td>Successful invoke of this method does not change the state. In order for the
397 * target audio attributes type to become effective, this method must be called before
398 * prepare() or prepareAsync().</p></td></tr>
Eric Laurent17cb2802010-08-03 03:50:02 -0700399 * <tr><td>setAudioSessionId </p></td>
400 * <td>{Idle} </p></td>
401 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
402 * Error} </p></td>
403 * <td>This method must be called in idle state as the audio session ID must be known before
404 * calling setDataSource. Calling it does not change the object state. </p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 * <tr><td>setAudioStreamType </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700406 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 * PlaybackCompleted}</p></td>
408 * <td>{Error}</p></td>
James Dong9d963542010-06-03 10:36:04 -0700409 * <td>Successful invoke of this method does not change the state. In order for the
410 * target audio stream type to become effective, this method must be called before
411 * prepare() or prepareAsync().</p></td></tr>
Eric Laurent17cb2802010-08-03 03:50:02 -0700412 * <tr><td>setAuxEffectSendLevel </p></td>
413 * <td>any</p></td>
414 * <td>{} </p></td>
415 * <td>Calling this method does not change the object state. </p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 * <tr><td>setDataSource </p></td>
417 * <td>{Idle} </p></td>
418 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
419 * Error} </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700420 * <td>Successful invoke of this method in a valid state transfers the
421 * object to the <em>Initialized</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 * invalid state throws an IllegalStateException.</p></td></tr>
423 * <tr><td>setDisplay </p></td>
424 * <td>any </p></td>
425 * <td>{} </p></td>
426 * <td>This method can be called in any state and calling it does not change
427 * the object state. </p></td></tr>
Jamie Gennisb283dc62011-08-28 16:28:08 -0700428 * <tr><td>setSurface </p></td>
Glenn Kastencc562a32011-02-08 17:26:17 -0800429 * <td>any </p></td>
430 * <td>{} </p></td>
431 * <td>This method can be called in any state and calling it does not change
432 * the object state. </p></td></tr>
James Dong454014e2012-04-28 16:03:55 -0700433 * <tr><td>setVideoScalingMode </p></td>
434 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
435 * <td>{Idle, Error}</p></td>
436 * <td>Successful invoke of this method does not change the state.</p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 * <tr><td>setLooping </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700438 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 * PlaybackCompleted}</p></td>
440 * <td>{Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700441 * <td>Successful invoke of this method in a valid state does not change
442 * the state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
444 * <tr><td>isLooping </p></td>
445 * <td>any </p></td>
446 * <td>{} </p></td>
447 * <td>This method can be called in any state and calling it does not change
448 * the object state. </p></td></tr>
449 * <tr><td>setOnBufferingUpdateListener </p></td>
450 * <td>any </p></td>
451 * <td>{} </p></td>
452 * <td>This method can be called in any state and calling it does not change
453 * the object state. </p></td></tr>
454 * <tr><td>setOnCompletionListener </p></td>
455 * <td>any </p></td>
456 * <td>{} </p></td>
457 * <td>This method can be called in any state and calling it does not change
458 * the object state. </p></td></tr>
459 * <tr><td>setOnErrorListener </p></td>
460 * <td>any </p></td>
461 * <td>{} </p></td>
462 * <td>This method can be called in any state and calling it does not change
463 * the object state. </p></td></tr>
464 * <tr><td>setOnPreparedListener </p></td>
465 * <td>any </p></td>
466 * <td>{} </p></td>
467 * <td>This method can be called in any state and calling it does not change
468 * the object state. </p></td></tr>
469 * <tr><td>setOnSeekCompleteListener </p></td>
470 * <td>any </p></td>
471 * <td>{} </p></td>
472 * <td>This method can be called in any state and calling it does not change
473 * the object state. </p></td></tr>
474 * <tr><td>setScreenOnWhilePlaying</></td>
475 * <td>any </p></td>
476 * <td>{} </p></td>
477 * <td>This method can be called in any state and calling it does not change
478 * the object state. </p></td></tr>
Wei Jiad93fcf42015-02-09 16:05:53 -0800479 * <tr><td>setPlaybackRate</p></td>
480 * <td>any </p></td>
481 * <td>{} </p></td>
482 * <td>This method can be called in any state and calling it does not change
483 * the object state. </p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 * <tr><td>setVolume </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700485 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 * PlaybackCompleted}</p></td>
487 * <td>{Error}</p></td>
488 * <td>Successful invoke of this method does not change the state.
489 * <tr><td>setWakeMode </p></td>
490 * <td>any </p></td>
491 * <td>{} </p></td>
492 * <td>This method can be called in any state and calling it does not change
493 * the object state.</p></td></tr>
494 * <tr><td>start </p></td>
495 * <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
496 * <td>{Idle, Initialized, Stopped, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700497 * <td>Successful invoke of this method in a valid state transfers the
498 * object to the <em>Started</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
500 * <tr><td>stop </p></td>
501 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
502 * <td>{Idle, Initialized, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700503 * <td>Successful invoke of this method in a valid state transfers the
504 * object to the <em>Stopped</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
Insun Kang41f3f712012-02-16 20:28:27 +0900506 * <tr><td>getTrackInfo </p></td>
507 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
508 * <td>{Idle, Initialized, Error}</p></td>
509 * <td>Successful invoke of this method does not change the state.</p></td></tr>
James Dong7a9734d2012-04-19 13:30:20 -0700510 * <tr><td>addTimedTextSource </p></td>
Insun Kang41f3f712012-02-16 20:28:27 +0900511 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
512 * <td>{Idle, Initialized, Error}</p></td>
513 * <td>Successful invoke of this method does not change the state.</p></td></tr>
514 * <tr><td>selectTrack </p></td>
515 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
516 * <td>{Idle, Initialized, Error}</p></td>
517 * <td>Successful invoke of this method does not change the state.</p></td></tr>
James Dong7a9734d2012-04-19 13:30:20 -0700518 * <tr><td>deselectTrack </p></td>
Insun Kang41f3f712012-02-16 20:28:27 +0900519 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
520 * <td>{Idle, Initialized, Error}</p></td>
521 * <td>Successful invoke of this method does not change the state.</p></td></tr>
Eric Laurent619346f2010-06-21 09:27:30 -0700522 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 * </table>
524 *
525 * <a name="Permissions"></a>
526 * <h3>Permissions</h3>
527 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
528 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
529 * element.
530 *
Dave Burkefc301b02011-08-30 14:39:17 +0100531 * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
532 * when used with network-based content.
533 *
James Dong9ddb7882011-06-14 14:01:57 -0700534 * <a name="Callbacks"></a>
535 * <h3>Callbacks</h3>
536 * <p>Applications may want to register for informational and error
537 * events in order to be informed of some internal state update and
538 * possible runtime errors during playback or streaming. Registration for
539 * these events is done by properly setting the appropriate listeners (via calls
540 * to
541 * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
542 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
543 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
544 * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
James Dongd52ad9c2011-06-14 18:20:53 -0700545 * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
James Dong9ddb7882011-06-14 14:01:57 -0700546 * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
547 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
548 * In order to receive the respective callback
549 * associated with these listeners, applications are required to create
550 * MediaPlayer objects on a thread with its own Looper running (main UI
551 * thread by default has a Looper running).
552 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 */
Lajos Molnar484ff7a92013-08-15 11:37:47 -0700554public class MediaPlayer implements SubtitleController.Listener
Nicolas Catania32f82772009-06-11 16:33:49 -0700555{
Nicolas Catania9193e082009-07-06 12:43:36 -0700556 /**
557 Constant to retrieve only the new metadata since the last
558 call.
559 // FIXME: unhide.
560 // FIXME: add link to getMetadata(boolean, boolean)
561 {@hide}
562 */
563 public static final boolean METADATA_UPDATE_ONLY = true;
564
565 /**
566 Constant to retrieve all the metadata.
567 // FIXME: unhide.
568 // FIXME: add link to getMetadata(boolean, boolean)
569 {@hide}
570 */
571 public static final boolean METADATA_ALL = false;
572
573 /**
574 Constant to enable the metadata filter during retrieval.
575 // FIXME: unhide.
576 // FIXME: add link to getMetadata(boolean, boolean)
577 {@hide}
578 */
579 public static final boolean APPLY_METADATA_FILTER = true;
580
581 /**
582 Constant to disable the metadata filter during retrieval.
583 // FIXME: unhide.
584 // FIXME: add link to getMetadata(boolean, boolean)
585 {@hide}
586 */
587 public static final boolean BYPASS_METADATA_FILTER = false;
588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 static {
590 System.loadLibrary("media_jni");
Marco Nelissen4935d052009-08-03 11:12:58 -0700591 native_init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
Nicolas Catania32f82772009-06-11 16:33:49 -0700593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 private final static String TAG = "MediaPlayer";
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700595 // Name of the remote interface for the media player. Must be kept
596 // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
597 // macro invocation in IMediaPlayer.cpp
598 private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
Nicolas Catania32f82772009-06-11 16:33:49 -0700599
Ashok Bhat075e9a12014-01-06 13:45:09 +0000600 private long mNativeContext; // accessed by native methods
601 private long mNativeSurfaceTexture; // accessed by native methods
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 private int mListenerContext; // accessed by native methods
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700603 private SurfaceHolder mSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 private EventHandler mEventHandler;
605 private PowerManager.WakeLock mWakeLock = null;
606 private boolean mScreenOnWhilePlaying;
607 private boolean mStayAwake;
John Spurlock1af30c72014-03-10 08:33:35 -0400608 private final IAppOpsService mAppOps;
609 private int mStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE;
John Spurlock7b414672014-07-18 13:02:39 -0400610 private int mUsage = -1;
John Spurlockbbfd31a2015-02-18 11:58:14 -0500611 private boolean mBypassInterruptionPolicy;
Nicolas Catania32f82772009-06-11 16:33:49 -0700612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 /**
Nicolas Catania32f82772009-06-11 16:33:49 -0700614 * Default constructor. Consider using one of the create() methods for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 * synchronously instantiating a MediaPlayer from a Uri or resource.
616 * <p>When done with the MediaPlayer, you should call {@link #release()},
617 * to free the resources. If not released, too many MediaPlayer instances may
618 * result in an exception.</p>
619 */
620 public MediaPlayer() {
Nicolas Catania32f82772009-06-11 16:33:49 -0700621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 Looper looper;
623 if ((looper = Looper.myLooper()) != null) {
624 mEventHandler = new EventHandler(this, looper);
625 } else if ((looper = Looper.getMainLooper()) != null) {
626 mEventHandler = new EventHandler(this, looper);
627 } else {
628 mEventHandler = null;
629 }
630
Lajos Molnar3d998562013-08-15 17:05:05 -0700631 mTimeProvider = new TimeProvider(this);
Lajos Molnar484ff7a92013-08-15 11:37:47 -0700632 mOutOfBandSubtitleTracks = new Vector<SubtitleTrack>();
633 mOpenSubtitleSources = new Vector<InputStream>();
634 mInbandSubtitleTracks = new SubtitleTrack[0];
John Spurlock1af30c72014-03-10 08:33:35 -0400635 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
636 mAppOps = IAppOpsService.Stub.asInterface(b);
Lajos Molnar3d998562013-08-15 17:05:05 -0700637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 /* Native setup requires a weak reference to our object.
639 * It's easier to create it here than in C++.
640 */
641 native_setup(new WeakReference<MediaPlayer>(this));
642 }
Dave Sparks8b0b1742009-05-29 09:01:20 -0700643
644 /*
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700645 * Update the MediaPlayer SurfaceTexture.
646 * Call after setting a new display surface.
Dave Sparks8b0b1742009-05-29 09:01:20 -0700647 */
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700648 private native void _setVideoSurface(Surface surface);
Nicolas Catania32f82772009-06-11 16:33:49 -0700649
Insun Kang41f3f712012-02-16 20:28:27 +0900650 /* Do not change these values (starting with INVOKE_ID) without updating
651 * their counterparts in include/media/mediaplayer.h!
652 */
653 private static final int INVOKE_ID_GET_TRACK_INFO = 1;
654 private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
655 private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
656 private static final int INVOKE_ID_SELECT_TRACK = 4;
James Dong7a9734d2012-04-19 13:30:20 -0700657 private static final int INVOKE_ID_DESELECT_TRACK = 5;
James Dong454014e2012-04-28 16:03:55 -0700658 private static final int INVOKE_ID_SET_VIDEO_SCALE_MODE = 6;
Robert Shih464da702014-05-29 10:54:32 -0700659 private static final int INVOKE_ID_GET_SELECTED_TRACK = 7;
Insun Kang41f3f712012-02-16 20:28:27 +0900660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 /**
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700662 * Create a request parcel which can be routed to the native media
663 * player using {@link #invoke(Parcel, Parcel)}. The Parcel
664 * returned has the proper InterfaceToken set. The caller should
665 * not overwrite that token, i.e it can only append data to the
666 * Parcel.
667 *
668 * @return A parcel suitable to hold a request for the native
669 * player.
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700670 * {@hide}
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700671 */
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700672 public Parcel newRequest() {
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700673 Parcel parcel = Parcel.obtain();
674 parcel.writeInterfaceToken(IMEDIA_PLAYER);
675 return parcel;
676 }
677
678 /**
679 * Invoke a generic method on the native player using opaque
680 * parcels for the request and reply. Both payloads' format is a
681 * convention between the java caller and the native player.
682 * Must be called after setDataSource to make sure a native player
James Dong7a9734d2012-04-19 13:30:20 -0700683 * exists. On failure, a RuntimeException is thrown.
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700684 *
685 * @param request Parcel with the data for the extension. The
686 * caller must use {@link #newRequest()} to get one.
687 *
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700688 * @param reply Output parcel with the data returned by the
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700689 * native player.
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700690 * {@hide}
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700691 */
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700692 public void invoke(Parcel request, Parcel reply) {
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700693 int retcode = native_invoke(request, reply);
694 reply.setDataPosition(0);
James Dong7a9734d2012-04-19 13:30:20 -0700695 if (retcode != 0) {
696 throw new RuntimeException("failure code: " + retcode);
697 }
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700698 }
699
700 /**
Glenn Kastencc562a32011-02-08 17:26:17 -0800701 * Sets the {@link SurfaceHolder} to use for displaying the video
Gloria Wang91784c992011-08-09 15:29:34 -0700702 * portion of the media.
Nicolas Catania32f82772009-06-11 16:33:49 -0700703 *
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700704 * Either a surface holder or surface must be set if a display or video sink
Jamie Gennisb283dc62011-08-28 16:28:08 -0700705 * is needed. Not calling this method or {@link #setSurface(Surface)}
Glenn Kastencc562a32011-02-08 17:26:17 -0800706 * when playing back a video will result in only the audio track being played.
Gloria Wang91784c992011-08-09 15:29:34 -0700707 * A null surface holder or surface will result in only the audio track being
708 * played.
Glenn Kasten5c2faf32011-06-27 10:10:19 -0700709 *
710 * @param sh the SurfaceHolder to use for video display
Glenn Kastencc562a32011-02-08 17:26:17 -0800711 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 public void setDisplay(SurfaceHolder sh) {
713 mSurfaceHolder = sh;
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700714 Surface surface;
Dave Sparks8b0b1742009-05-29 09:01:20 -0700715 if (sh != null) {
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700716 surface = sh.getSurface();
Dave Sparks8b0b1742009-05-29 09:01:20 -0700717 } else {
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700718 surface = null;
Dave Sparks8b0b1742009-05-29 09:01:20 -0700719 }
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700720 _setVideoSurface(surface);
Glenn Kastencc562a32011-02-08 17:26:17 -0800721 updateSurfaceScreenOn();
722 }
723
724 /**
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700725 * Sets the {@link Surface} to be used as the sink for the video portion of
Jamie Gennisb283dc62011-08-28 16:28:08 -0700726 * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but
727 * does not support {@link #setScreenOnWhilePlaying(boolean)}. Setting a
728 * Surface will un-set any Surface or SurfaceHolder that was previously set.
Gloria Wang91784c992011-08-09 15:29:34 -0700729 * A null surface will result in only the audio track being played.
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700730 *
Jamie Gennisb283dc62011-08-28 16:28:08 -0700731 * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
732 * returned from {@link SurfaceTexture#getTimestamp()} will have an
733 * unspecified zero point. These timestamps cannot be directly compared
734 * between different media sources, different instances of the same media
735 * source, or multiple runs of the same program. The timestamp is normally
736 * monotonically increasing and is unaffected by time-of-day adjustments,
737 * but it is reset when the position is set.
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700738 *
Jamie Gennisb283dc62011-08-28 16:28:08 -0700739 * @param surface The {@link Surface} to be used for the video portion of
740 * the media.
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700741 */
742 public void setSurface(Surface surface) {
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700743 if (mScreenOnWhilePlaying && surface != null) {
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700744 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
745 }
746 mSurfaceHolder = null;
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700747 _setVideoSurface(surface);
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700748 updateSurfaceScreenOn();
749 }
750
James Dong454014e2012-04-28 16:03:55 -0700751 /* Do not change these video scaling mode values below without updating
752 * their counterparts in system/window.h! Please do not forget to update
753 * {@link #isVideoScalingModeSupported} when new video scaling modes
754 * are added.
755 */
756 /**
757 * Specifies a video scaling mode. The content is stretched to the
758 * surface rendering area. When the surface has the same aspect ratio
759 * as the content, the aspect ratio of the content is maintained;
760 * otherwise, the aspect ratio of the content is not maintained when video
Jeff Smitha45746e2012-07-19 14:19:24 -0500761 * is being rendered. Unlike {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING},
James Dong454014e2012-04-28 16:03:55 -0700762 * there is no content cropping with this video scaling mode.
763 */
764 public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
765
766 /**
767 * Specifies a video scaling mode. The content is scaled, maintaining
768 * its aspect ratio. The whole surface area is always used. When the
769 * aspect ratio of the content is the same as the surface, no content
770 * is cropped; otherwise, content is cropped to fit the surface.
771 */
772 public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2;
773 /**
774 * Sets video scaling mode. To make the target video scaling mode
775 * effective during playback, this method must be called after
776 * data source is set. If not called, the default video
777 * scaling mode is {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}.
778 *
779 * <p> The supported video scaling modes are:
780 * <ul>
781 * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}
782 * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}
783 * </ul>
784 *
785 * @param mode target video scaling mode. Most be one of the supported
786 * video scaling modes; otherwise, IllegalArgumentException will be thrown.
787 *
788 * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT
789 * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
790 */
791 public void setVideoScalingMode(int mode) {
Bryan Mawhinney79a9cd42012-05-18 00:15:56 +0100792 if (!isVideoScalingModeSupported(mode)) {
James Dong454014e2012-04-28 16:03:55 -0700793 final String msg = "Scaling mode " + mode + " is not supported";
794 throw new IllegalArgumentException(msg);
795 }
796 Parcel request = Parcel.obtain();
797 Parcel reply = Parcel.obtain();
Insun Kangbe0ea962012-05-04 20:52:57 +0900798 try {
799 request.writeInterfaceToken(IMEDIA_PLAYER);
800 request.writeInt(INVOKE_ID_SET_VIDEO_SCALE_MODE);
Bryan Mawhinneyc3a5cf92012-05-27 17:42:46 +0100801 request.writeInt(mode);
Insun Kangbe0ea962012-05-04 20:52:57 +0900802 invoke(request, reply);
803 } finally {
804 request.recycle();
805 reply.recycle();
806 }
James Dong454014e2012-04-28 16:03:55 -0700807 }
808
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700809 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 * Convenience method to create a MediaPlayer for a given Uri.
811 * On success, {@link #prepare()} will already have been called and must not be called again.
812 * <p>When done with the MediaPlayer, you should call {@link #release()},
813 * to free the resources. If not released, too many MediaPlayer instances will
814 * result in an exception.</p>
Jean-Michel Trivi79f5cd12014-07-15 15:42:25 -0700815 * <p>Note that since {@link #prepare()} is called automatically in this method,
816 * you cannot change the audio stream type (see {@link #setAudioStreamType(int)}), audio
817 * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
818 * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
Nicolas Catania32f82772009-06-11 16:33:49 -0700819 *
820 * @param context the Context to use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 * @param uri the Uri from which to get the datasource
822 * @return a MediaPlayer object, or null if creation failed
823 */
824 public static MediaPlayer create(Context context, Uri uri) {
825 return create (context, uri, null);
826 }
Nicolas Catania32f82772009-06-11 16:33:49 -0700827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 /**
829 * Convenience method to create a MediaPlayer for a given Uri.
830 * On success, {@link #prepare()} will already have been called and must not be called again.
831 * <p>When done with the MediaPlayer, you should call {@link #release()},
832 * to free the resources. If not released, too many MediaPlayer instances will
833 * result in an exception.</p>
Jean-Michel Trivi79f5cd12014-07-15 15:42:25 -0700834 * <p>Note that since {@link #prepare()} is called automatically in this method,
835 * you cannot change the audio stream type (see {@link #setAudioStreamType(int)}), audio
836 * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
837 * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
Nicolas Catania32f82772009-06-11 16:33:49 -0700838 *
839 * @param context the Context to use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 * @param uri the Uri from which to get the datasource
841 * @param holder the SurfaceHolder to use for displaying the video
842 * @return a MediaPlayer object, or null if creation failed
843 */
844 public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
Jean-Michel Trivid70ad7a2014-07-15 16:34:17 -0700845 int s = AudioSystem.newAudioSessionId();
846 return create(context, uri, holder, null, s > 0 ? s : 0);
847 }
848
849 /**
850 * Same factory method as {@link #create(Context, Uri, SurfaceHolder)} but that lets you specify
851 * the audio attributes and session ID to be used by the new MediaPlayer instance.
852 * @param context the Context to use
853 * @param uri the Uri from which to get the datasource
854 * @param holder the SurfaceHolder to use for displaying the video, may be null.
855 * @param audioAttributes the {@link AudioAttributes} to be used by the media player.
856 * @param audioSessionId the audio session ID to be used by the media player,
Jean-Michel Trivi289cc8e2014-07-18 18:45:32 -0700857 * see {@link AudioManager#generateAudioSessionId()} to obtain a new session.
Jean-Michel Trivid70ad7a2014-07-15 16:34:17 -0700858 * @return a MediaPlayer object, or null if creation failed
859 */
860 public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder,
861 AudioAttributes audioAttributes, int audioSessionId) {
Nicolas Catania32f82772009-06-11 16:33:49 -0700862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 try {
864 MediaPlayer mp = new MediaPlayer();
Jean-Michel Trivid70ad7a2014-07-15 16:34:17 -0700865 final AudioAttributes aa = audioAttributes != null ? audioAttributes :
866 new AudioAttributes.Builder().build();
867 mp.setAudioAttributes(aa);
868 mp.setAudioSessionId(audioSessionId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 mp.setDataSource(context, uri);
870 if (holder != null) {
871 mp.setDisplay(holder);
872 }
873 mp.prepare();
874 return mp;
875 } catch (IOException ex) {
876 Log.d(TAG, "create failed:", ex);
877 // fall through
878 } catch (IllegalArgumentException ex) {
879 Log.d(TAG, "create failed:", ex);
880 // fall through
881 } catch (SecurityException ex) {
882 Log.d(TAG, "create failed:", ex);
883 // fall through
884 }
885
886 return null;
887 }
888
Glenn Kastencc562a32011-02-08 17:26:17 -0800889 // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 /**
892 * Convenience method to create a MediaPlayer for a given resource id.
893 * On success, {@link #prepare()} will already have been called and must not be called again.
894 * <p>When done with the MediaPlayer, you should call {@link #release()},
895 * to free the resources. If not released, too many MediaPlayer instances will
896 * result in an exception.</p>
Jean-Michel Trivi79f5cd12014-07-15 15:42:25 -0700897 * <p>Note that since {@link #prepare()} is called automatically in this method,
898 * you cannot change the audio stream type (see {@link #setAudioStreamType(int)}), audio
899 * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
900 * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
Nicolas Catania32f82772009-06-11 16:33:49 -0700901 *
902 * @param context the Context to use
903 * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 * the resource to use as the datasource
905 * @return a MediaPlayer object, or null if creation failed
906 */
907 public static MediaPlayer create(Context context, int resid) {
Jean-Michel Trivid70ad7a2014-07-15 16:34:17 -0700908 int s = AudioSystem.newAudioSessionId();
909 return create(context, resid, null, s > 0 ? s : 0);
910 }
911
912 /**
913 * Same factory method as {@link #create(Context, int)} but that lets you specify the audio
914 * attributes and session ID to be used by the new MediaPlayer instance.
915 * @param context the Context to use
916 * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
917 * the resource to use as the datasource
918 * @param audioAttributes the {@link AudioAttributes} to be used by the media player.
919 * @param audioSessionId the audio session ID to be used by the media player,
Jean-Michel Trivi289cc8e2014-07-18 18:45:32 -0700920 * see {@link AudioManager#generateAudioSessionId()} to obtain a new session.
Jean-Michel Trivid70ad7a2014-07-15 16:34:17 -0700921 * @return a MediaPlayer object, or null if creation failed
922 */
923 public static MediaPlayer create(Context context, int resid,
924 AudioAttributes audioAttributes, int audioSessionId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 try {
926 AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
927 if (afd == null) return null;
928
929 MediaPlayer mp = new MediaPlayer();
Jean-Michel Trivid70ad7a2014-07-15 16:34:17 -0700930
931 final AudioAttributes aa = audioAttributes != null ? audioAttributes :
932 new AudioAttributes.Builder().build();
933 mp.setAudioAttributes(aa);
934 mp.setAudioSessionId(audioSessionId);
935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
937 afd.close();
938 mp.prepare();
939 return mp;
940 } catch (IOException ex) {
941 Log.d(TAG, "create failed:", ex);
942 // fall through
943 } catch (IllegalArgumentException ex) {
944 Log.d(TAG, "create failed:", ex);
945 // fall through
946 } catch (SecurityException ex) {
947 Log.d(TAG, "create failed:", ex);
948 // fall through
949 }
950 return null;
951 }
Nicolas Catania32f82772009-06-11 16:33:49 -0700952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 /**
954 * Sets the data source as a content Uri.
Nicolas Catania32f82772009-06-11 16:33:49 -0700955 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 * @param context the Context to use when resolving the Uri
957 * @param uri the Content URI of the data you want to play
958 * @throws IllegalStateException if it is called in an invalid state
959 */
960 public void setDataSource(Context context, Uri uri)
961 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
Andreas Huber25643002010-01-28 11:19:57 -0800962 setDataSource(context, uri, null);
963 }
964
965 /**
966 * Sets the data source as a content Uri.
967 *
968 * @param context the Context to use when resolving the Uri
969 * @param uri the Content URI of the data you want to play
970 * @param headers the headers to be sent together with the request for the data
Ronghua Wu48db7832014-08-25 14:47:58 -0700971 * Note that the cross domain redirection is allowed by default, but that can be
972 * changed with key/value pairs through the headers parameter with
973 * "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value
974 * to disallow or allow cross domain redirection.
Andreas Huber25643002010-01-28 11:19:57 -0800975 * @throws IllegalStateException if it is called in an invalid state
Andreas Huber25643002010-01-28 11:19:57 -0800976 */
977 public void setDataSource(Context context, Uri uri, Map<String, String> headers)
Jeff Sharkey3b566b82014-11-12 10:39:56 -0800978 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
979 final String scheme = uri.getScheme();
980 if (ContentResolver.SCHEME_FILE.equals(scheme)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 setDataSource(uri.getPath());
982 return;
Jeff Sharkey3b566b82014-11-12 10:39:56 -0800983 } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)
984 && Settings.AUTHORITY.equals(uri.getAuthority())) {
985 // Redirect ringtones to go directly to underlying provider
986 uri = RingtoneManager.getActualDefaultRingtoneUri(context,
987 RingtoneManager.getDefaultType(uri));
Jeff Sharkey87d76f62014-12-09 15:27:19 -0800988 if (uri == null) {
989 throw new FileNotFoundException("Failed to resolve default ringtone");
990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 }
992
993 AssetFileDescriptor fd = null;
994 try {
995 ContentResolver resolver = context.getContentResolver();
996 fd = resolver.openAssetFileDescriptor(uri, "r");
997 if (fd == null) {
998 return;
999 }
1000 // Note: using getDeclaredLength so that our behavior is the same
1001 // as previous versions when the content provider is returning
1002 // a full file.
1003 if (fd.getDeclaredLength() < 0) {
1004 setDataSource(fd.getFileDescriptor());
1005 } else {
1006 setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
1007 }
1008 return;
1009 } catch (SecurityException ex) {
1010 } catch (IOException ex) {
1011 } finally {
1012 if (fd != null) {
1013 fd.close();
1014 }
1015 }
Dave Burkefc301b02011-08-30 14:39:17 +01001016
Marco Nelissena2df6052009-06-09 15:49:23 -07001017 Log.d(TAG, "Couldn't open file on client side, trying server side");
Andreas Huberd5f9fa52013-05-28 14:39:39 -07001018
Andreas Huber25643002010-01-28 11:19:57 -08001019 setDataSource(uri.toString(), headers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021
1022 /**
1023 * Sets the data source (file-path or http/rtsp URL) to use.
Nicolas Catania32f82772009-06-11 16:33:49 -07001024 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 * @param path the path of the file, or the http/rtsp URL of the stream you want to play
1026 * @throws IllegalStateException if it is called in an invalid state
Glenn Kasten55d1eea2012-03-09 11:02:31 -08001027 *
1028 * <p>When <code>path</code> refers to a local file, the file may actually be opened by a
1029 * process other than the calling application. This implies that the pathname
1030 * should be an absolute path (as any other process runs with unspecified current working
1031 * directory), and that the pathname should reference a world-readable file.
1032 * As an alternative, the application could first open the file for reading,
1033 * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 */
James Donge00b6f32012-04-11 21:18:43 -07001035 public void setDataSource(String path)
1036 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
1037 setDataSource(path, null, null);
1038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039
1040 /**
Andreas Huber25643002010-01-28 11:19:57 -08001041 * Sets the data source (file-path or http/rtsp URL) to use.
1042 *
1043 * @param path the path of the file, or the http/rtsp URL of the stream you want to play
1044 * @param headers the headers associated with the http request for the stream you want to play
1045 * @throws IllegalStateException if it is called in an invalid state
1046 * @hide pending API council
1047 */
James Dong17524dc2011-05-04 13:41:58 -07001048 public void setDataSource(String path, Map<String, String> headers)
Dave Burkefc301b02011-08-30 14:39:17 +01001049 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
James Dong17524dc2011-05-04 13:41:58 -07001050 {
Andreas Hubere4e7b482011-05-11 16:54:41 -07001051 String[] keys = null;
1052 String[] values = null;
1053
1054 if (headers != null) {
1055 keys = new String[headers.size()];
1056 values = new String[headers.size()];
1057
1058 int i = 0;
1059 for (Map.Entry<String, String> entry: headers.entrySet()) {
1060 keys[i] = entry.getKey();
1061 values[i] = entry.getValue();
1062 ++i;
1063 }
James Dong17524dc2011-05-04 13:41:58 -07001064 }
James Donge00b6f32012-04-11 21:18:43 -07001065 setDataSource(path, keys, values);
1066 }
1067
1068 private void setDataSource(String path, String[] keys, String[] values)
1069 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
Jeff Sharkeyc058a382013-02-19 14:44:41 -08001070 final Uri uri = Uri.parse(path);
Lajos Molnard504ab12014-08-18 14:26:55 -07001071 final String scheme = uri.getScheme();
1072 if ("file".equals(scheme)) {
Jeff Sharkeyc058a382013-02-19 14:44:41 -08001073 path = uri.getPath();
Lajos Molnard504ab12014-08-18 14:26:55 -07001074 } else if (scheme != null) {
1075 // handle non-file sources
1076 nativeSetDataSource(
1077 MediaHTTPService.createHttpServiceBinderIfNecessary(path),
1078 path,
1079 keys,
1080 values);
1081 return;
Jeff Sharkeyc058a382013-02-19 14:44:41 -08001082 }
1083
1084 final File file = new File(path);
James Donge00b6f32012-04-11 21:18:43 -07001085 if (file.exists()) {
1086 FileInputStream is = new FileInputStream(file);
1087 FileDescriptor fd = is.getFD();
1088 setDataSource(fd);
1089 is.close();
1090 } else {
Lajos Molnard504ab12014-08-18 14:26:55 -07001091 throw new IOException("setDataSource failed.");
James Donge00b6f32012-04-11 21:18:43 -07001092 }
James Dong17524dc2011-05-04 13:41:58 -07001093 }
1094
Andreas Huberd2506a52014-01-29 10:32:46 -08001095 private native void nativeSetDataSource(
1096 IBinder httpServiceBinder, String path, String[] keys, String[] values)
Dave Burkefc301b02011-08-30 14:39:17 +01001097 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
Andreas Huber25643002010-01-28 11:19:57 -08001098
1099 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
1101 * to close the file descriptor. It is safe to do so as soon as this call returns.
Nicolas Catania32f82772009-06-11 16:33:49 -07001102 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 * @param fd the FileDescriptor for the file you want to play
1104 * @throws IllegalStateException if it is called in an invalid state
1105 */
Nicolas Catania32f82772009-06-11 16:33:49 -07001106 public void setDataSource(FileDescriptor fd)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 throws IOException, IllegalArgumentException, IllegalStateException {
1108 // intentionally less than LONG_MAX
1109 setDataSource(fd, 0, 0x7ffffffffffffffL);
1110 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 /**
Kenny Root6ab180a2009-06-13 06:16:23 -05001113 * Sets the data source (FileDescriptor) to use. The FileDescriptor must be
1114 * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 * to close the file descriptor. It is safe to do so as soon as this call returns.
Nicolas Catania32f82772009-06-11 16:33:49 -07001116 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 * @param fd the FileDescriptor for the file you want to play
1118 * @param offset the offset into the file where the data to be played starts, in bytes
1119 * @param length the length in bytes of the data to be played
1120 * @throws IllegalStateException if it is called in an invalid state
1121 */
Andreas Huberd5f9fa52013-05-28 14:39:39 -07001122 public void setDataSource(FileDescriptor fd, long offset, long length)
1123 throws IOException, IllegalArgumentException, IllegalStateException {
Andreas Huberd5f9fa52013-05-28 14:39:39 -07001124 _setDataSource(fd, offset, length);
1125 }
1126
1127 private native void _setDataSource(FileDescriptor fd, long offset, long length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 throws IOException, IllegalArgumentException, IllegalStateException;
1129
1130 /**
Chris Watkins4eaa2932015-03-20 10:31:42 -07001131 * Sets the data source (MediaDataSource) to use.
1132 *
1133 * @param dataSource the MediaDataSource for the media you want to play
1134 * @throws IllegalStateException if it is called in an invalid state
1135 */
1136 public void setDataSource(MediaDataSource dataSource)
1137 throws IllegalArgumentException, IllegalStateException {
1138 _setDataSource(dataSource);
1139 }
1140
1141 private native void _setDataSource(MediaDataSource dataSource)
1142 throws IllegalArgumentException, IllegalStateException;
1143
1144 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 * Prepares the player for playback, synchronously.
Nicolas Catania32f82772009-06-11 16:33:49 -07001146 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 * After setting the datasource and the display surface, you need to either
1148 * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
1149 * which blocks until MediaPlayer is ready for playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07001150 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 * @throws IllegalStateException if it is called in an invalid state
1152 */
Robert Shihc42a96d2014-07-25 11:08:50 -07001153 public void prepare() throws IOException, IllegalStateException {
1154 _prepare();
1155 scanInternalSubtitleTracks();
1156 }
1157
1158 private native void _prepare() throws IOException, IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 /**
1161 * Prepares the player for playback, asynchronously.
Nicolas Catania32f82772009-06-11 16:33:49 -07001162 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 * After setting the datasource and the display surface, you need to either
1164 * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
1165 * which returns immediately, rather than blocking until enough data has been
1166 * buffered.
Nicolas Catania32f82772009-06-11 16:33:49 -07001167 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 * @throws IllegalStateException if it is called in an invalid state
1169 */
1170 public native void prepareAsync() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 /**
1173 * Starts or resumes playback. If playback had previously been paused,
1174 * playback will continue from where it was paused. If playback had
1175 * been stopped, or never started before, playback will start at the
1176 * beginning.
Nicolas Catania32f82772009-06-11 16:33:49 -07001177 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 * @throws IllegalStateException if it is called in an invalid state
1179 */
John Spurlock1af30c72014-03-10 08:33:35 -04001180 public void start() throws IllegalStateException {
1181 if (isRestricted()) {
1182 _setVolume(0, 0);
1183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 stayAwake(true);
1185 _start();
1186 }
1187
1188 private native void _start() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001189
John Spurlock1af30c72014-03-10 08:33:35 -04001190 private boolean isRestricted() {
John Spurlockbbfd31a2015-02-18 11:58:14 -05001191 if (mBypassInterruptionPolicy) {
1192 return false;
1193 }
John Spurlock1af30c72014-03-10 08:33:35 -04001194 try {
John Spurlock7b414672014-07-18 13:02:39 -04001195 final int usage = mUsage != -1 ? mUsage
1196 : AudioAttributes.usageForLegacyStreamType(getAudioStreamType());
1197 final int mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO, usage,
1198 Process.myUid(), ActivityThread.currentPackageName());
John Spurlock1af30c72014-03-10 08:33:35 -04001199 return mode != AppOpsManager.MODE_ALLOWED;
1200 } catch (RemoteException e) {
1201 return false;
1202 }
1203 }
1204
1205 private int getAudioStreamType() {
1206 if (mStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1207 mStreamType = _getAudioStreamType();
1208 }
1209 return mStreamType;
1210 }
1211
1212 private native int _getAudioStreamType() throws IllegalStateException;
1213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 /**
Nicolas Catania32f82772009-06-11 16:33:49 -07001215 * Stops playback after playback has been stopped or paused.
1216 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 * @throws IllegalStateException if the internal player engine has not been
1218 * initialized.
1219 */
1220 public void stop() throws IllegalStateException {
1221 stayAwake(false);
1222 _stop();
1223 }
1224
1225 private native void _stop() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 /**
1228 * Pauses playback. Call start() to resume.
Nicolas Catania32f82772009-06-11 16:33:49 -07001229 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 * @throws IllegalStateException if the internal player engine has not been
1231 * initialized.
1232 */
1233 public void pause() throws IllegalStateException {
1234 stayAwake(false);
1235 _pause();
1236 }
1237
1238 private native void _pause() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 /**
1241 * Set the low-level power management behavior for this MediaPlayer. This
1242 * can be used when the MediaPlayer is not playing through a SurfaceHolder
1243 * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
1244 * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
Nicolas Catania32f82772009-06-11 16:33:49 -07001245 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 * <p>This function has the MediaPlayer access the low-level power manager
1247 * service to control the device's power usage while playing is occurring.
1248 * The parameter is a combination of {@link android.os.PowerManager} wake flags.
1249 * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
1250 * permission.
1251 * By default, no attempt is made to keep the device awake during playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07001252 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 * @param context the Context to use
1254 * @param mode the power/wake mode to set
1255 * @see android.os.PowerManager
1256 */
1257 public void setWakeMode(Context context, int mode) {
1258 boolean washeld = false;
1259 if (mWakeLock != null) {
1260 if (mWakeLock.isHeld()) {
1261 washeld = true;
1262 mWakeLock.release();
1263 }
1264 mWakeLock = null;
1265 }
1266
1267 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1268 mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
1269 mWakeLock.setReferenceCounted(false);
1270 if (washeld) {
1271 mWakeLock.acquire();
1272 }
1273 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 /**
1276 * Control whether we should use the attached SurfaceHolder to keep the
1277 * screen on while video playback is occurring. This is the preferred
1278 * method over {@link #setWakeMode} where possible, since it doesn't
1279 * require that the application have permission for low-level wake lock
1280 * access.
Nicolas Catania32f82772009-06-11 16:33:49 -07001281 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 * @param screenOn Supply true to keep the screen on, false to allow it
1283 * to turn off.
1284 */
1285 public void setScreenOnWhilePlaying(boolean screenOn) {
1286 if (mScreenOnWhilePlaying != screenOn) {
Ted Bonkenburg0de171b2011-07-15 15:10:10 -07001287 if (screenOn && mSurfaceHolder == null) {
1288 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
Glenn Kasten817c1612011-04-13 08:11:47 -07001289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 mScreenOnWhilePlaying = screenOn;
1291 updateSurfaceScreenOn();
1292 }
1293 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 private void stayAwake(boolean awake) {
1296 if (mWakeLock != null) {
1297 if (awake && !mWakeLock.isHeld()) {
1298 mWakeLock.acquire();
1299 } else if (!awake && mWakeLock.isHeld()) {
1300 mWakeLock.release();
1301 }
1302 }
1303 mStayAwake = awake;
1304 updateSurfaceScreenOn();
1305 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 private void updateSurfaceScreenOn() {
1308 if (mSurfaceHolder != null) {
1309 mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1310 }
1311 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 /**
1314 * Returns the width of the video.
Nicolas Catania32f82772009-06-11 16:33:49 -07001315 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 * @return the width of the video, or 0 if there is no video,
Jean-Baptiste Queruea5f7672009-09-16 15:06:25 -07001317 * no display surface was set, or the width has not been determined
1318 * yet. The OnVideoSizeChangedListener can be registered via
1319 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1320 * to provide a notification when the width is available.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 */
1322 public native int getVideoWidth();
Nicolas Catania32f82772009-06-11 16:33:49 -07001323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 /**
1325 * Returns the height of the video.
Nicolas Catania32f82772009-06-11 16:33:49 -07001326 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 * @return the height of the video, or 0 if there is no video,
Jean-Baptiste Queruea5f7672009-09-16 15:06:25 -07001328 * no display surface was set, or the height has not been determined
1329 * yet. The OnVideoSizeChangedListener can be registered via
1330 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1331 * to provide a notification when the height is available.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 */
1333 public native int getVideoHeight();
Nicolas Catania32f82772009-06-11 16:33:49 -07001334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 /**
1336 * Checks whether the MediaPlayer is playing.
Nicolas Catania32f82772009-06-11 16:33:49 -07001337 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 * @return true if currently playing, false otherwise
Scott Main099fd802012-07-03 16:32:11 -07001339 * @throws IllegalStateException if the internal player engine has not been
1340 * initialized or has been released.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 */
1342 public native boolean isPlaying();
Nicolas Catania32f82772009-06-11 16:33:49 -07001343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 /**
Wei Jiad93fcf42015-02-09 16:05:53 -08001345 * Specifies resampling as audio mode for variable rate playback, i.e.,
1346 * resample the waveform based on the requested playback rate to get
1347 * a new waveform, and play back the new waveform at the original sampling
1348 * frequency.
1349 * When rate is larger than 1.0, pitch becomes higher.
1350 * When rate is smaller than 1.0, pitch becomes lower.
1351 */
1352 public static final int PLAYBACK_RATE_AUDIO_MODE_RESAMPLE = 0;
1353
1354 /**
1355 * Specifies time stretching as audio mode for variable rate playback.
1356 * Time stretching changes the duration of the audio samples without
1357 * affecting its pitch.
1358 * FIXME: implement time strectching.
1359 * @hide
1360 */
1361 public static final int PLAYBACK_RATE_AUDIO_MODE_STRETCH = 1;
1362
1363 /** @hide */
1364 @IntDef(
1365 value = {
1366 PLAYBACK_RATE_AUDIO_MODE_RESAMPLE,
1367 PLAYBACK_RATE_AUDIO_MODE_STRETCH })
1368 @Retention(RetentionPolicy.SOURCE)
1369 public @interface PlaybackRateAudioMode {}
1370
1371 /**
1372 * Sets playback rate and audio mode.
1373 *
1374 * <p> The supported audio modes are:
1375 * <ul>
1376 * <li> {@link #PLAYBACK_RATE_AUDIO_MODE_RESAMPLE}
1377 * </ul>
1378 *
1379 * @param rate the ratio between desired playback rate and normal one.
1380 * @param audioMode audio playback mode. Must be one of the supported
1381 * audio modes.
1382 *
1383 * @throws IllegalStateException if the internal player engine has not been
1384 * initialized.
1385 * @throws IllegalArgumentException if audioMode is not supported.
1386 */
1387 public void setPlaybackRate(float rate, @PlaybackRateAudioMode int audioMode) {
1388 if (!isAudioPlaybackModeSupported(audioMode)) {
1389 final String msg = "Audio playback mode " + audioMode + " is not supported";
1390 throw new IllegalArgumentException(msg);
1391 }
1392 _setPlaybackRate(rate);
1393 }
1394
1395 private native void _setPlaybackRate(float rate) throws IllegalStateException;
1396
1397 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 * Seeks to specified time position.
Nicolas Catania32f82772009-06-11 16:33:49 -07001399 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 * @param msec the offset in milliseconds from the start to seek to
1401 * @throws IllegalStateException if the internal player engine has not been
1402 * initialized
1403 */
1404 public native void seekTo(int msec) throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 /**
1407 * Gets the current playback position.
Nicolas Catania32f82772009-06-11 16:33:49 -07001408 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 * @return the current position in milliseconds
1410 */
1411 public native int getCurrentPosition();
Nicolas Catania32f82772009-06-11 16:33:49 -07001412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 /**
1414 * Gets the duration of the file.
Nicolas Catania32f82772009-06-11 16:33:49 -07001415 *
Andreas Huber7cd281c2013-04-11 11:07:03 -07001416 * @return the duration in milliseconds, if no duration is available
1417 * (for example, if streaming live content), -1 is returned.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 */
1419 public native int getDuration();
Nicolas Catania32f82772009-06-11 16:33:49 -07001420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 /**
Nicolas Catania9193e082009-07-06 12:43:36 -07001422 * Gets the media metadata.
1423 *
1424 * @param update_only controls whether the full set of available
1425 * metadata is returned or just the set that changed since the
1426 * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1427 * #METADATA_ALL}.
1428 *
1429 * @param apply_filter if true only metadata that matches the
1430 * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1431 * #BYPASS_METADATA_FILTER}.
1432 *
1433 * @return The metadata, possibly empty. null if an error occured.
1434 // FIXME: unhide.
1435 * {@hide}
1436 */
1437 public Metadata getMetadata(final boolean update_only,
1438 final boolean apply_filter) {
Nicolas Catania5d55c712009-07-09 09:21:33 -07001439 Parcel reply = Parcel.obtain();
1440 Metadata data = new Metadata();
1441
1442 if (!native_getMetadata(update_only, apply_filter, reply)) {
1443 reply.recycle();
1444 return null;
1445 }
1446
1447 // Metadata takes over the parcel, don't recycle it unless
1448 // there is an error.
1449 if (!data.parse(reply)) {
1450 reply.recycle();
1451 return null;
1452 }
1453 return data;
Nicolas Catania9193e082009-07-06 12:43:36 -07001454 }
1455
1456 /**
1457 * Set a filter for the metadata update notification and update
1458 * retrieval. The caller provides 2 set of metadata keys, allowed
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001459 * and blocked. The blocked set always takes precedence over the
1460 * allowed one.
Nicolas Catania9193e082009-07-06 12:43:36 -07001461 * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001462 * shorthands to allow/block all or no metadata.
Nicolas Catania9193e082009-07-06 12:43:36 -07001463 *
1464 * By default, there is no filter set.
1465 *
1466 * @param allow Is the set of metadata the client is interested
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001467 * in receiving new notifications for.
1468 * @param block Is the set of metadata the client is not interested
1469 * in receiving new notifications for.
Nicolas Catania9193e082009-07-06 12:43:36 -07001470 * @return The call status code.
1471 *
1472 // FIXME: unhide.
1473 * {@hide}
1474 */
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001475 public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1476 // Do our serialization manually instead of calling
1477 // Parcel.writeArray since the sets are made of the same type
1478 // we avoid paying the price of calling writeValue (used by
1479 // writeArray) which burns an extra int per element to encode
1480 // the type.
1481 Parcel request = newRequest();
1482
1483 // The parcel starts already with an interface token. There
1484 // are 2 filters. Each one starts with a 4bytes number to
1485 // store the len followed by a number of int (4 bytes as well)
1486 // representing the metadata type.
1487 int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1488
1489 if (request.dataCapacity() < capacity) {
1490 request.setDataCapacity(capacity);
1491 }
1492
1493 request.writeInt(allow.size());
1494 for(Integer t: allow) {
1495 request.writeInt(t);
1496 }
1497 request.writeInt(block.size());
1498 for(Integer t: block) {
1499 request.writeInt(t);
1500 }
1501 return native_setMetadataFilter(request);
Nicolas Catania9193e082009-07-06 12:43:36 -07001502 }
1503
1504 /**
Marco Nelissen84b83202012-02-28 16:07:44 -08001505 * Set the MediaPlayer to start when this MediaPlayer finishes playback
1506 * (i.e. reaches the end of the stream).
1507 * The media framework will attempt to transition from this player to
1508 * the next as seamlessly as possible. The next player can be set at
1509 * any time before completion. The next player must be prepared by the
1510 * app, and the application should not call start() on it.
1511 * The next MediaPlayer must be different from 'this'. An exception
1512 * will be thrown if next == this.
1513 * The application may call setNextMediaPlayer(null) to indicate no
1514 * next player should be started at the end of playback.
1515 * If the current player is looping, it will keep looping and the next
1516 * player will not be started.
1517 *
1518 * @param next the player to start after this one completes playback.
1519 *
Marco Nelissen84b83202012-02-28 16:07:44 -08001520 */
1521 public native void setNextMediaPlayer(MediaPlayer next);
1522
1523 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 * Releases resources associated with this MediaPlayer object.
1525 * It is considered good practice to call this method when you're
James Dong89ca6982011-11-14 19:01:26 -08001526 * done using the MediaPlayer. In particular, whenever an Activity
1527 * of an application is paused (its onPause() method is called),
1528 * or stopped (its onStop() method is called), this method should be
1529 * invoked to release the MediaPlayer object, unless the application
1530 * has a special need to keep the object around. In addition to
1531 * unnecessary resources (such as memory and instances of codecs)
1532 * being held, failure to call this method immediately if a
1533 * MediaPlayer object is no longer needed may also lead to
1534 * continuous battery consumption for mobile devices, and playback
1535 * failure for other applications if no multiple instances of the
1536 * same codec are supported on a device. Even if multiple instances
1537 * of the same codec are supported, some performance degradation
1538 * may be expected when unnecessary multiple instances are used
1539 * at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 */
1541 public void release() {
1542 stayAwake(false);
1543 updateSurfaceScreenOn();
1544 mOnPreparedListener = null;
1545 mOnBufferingUpdateListener = null;
1546 mOnCompletionListener = null;
1547 mOnSeekCompleteListener = null;
1548 mOnErrorListener = null;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001549 mOnInfoListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 mOnVideoSizeChangedListener = null;
Gloria Wang162ee492011-04-11 17:23:27 -07001551 mOnTimedTextListener = null;
Lajos Molnara67a4432013-09-06 06:30:35 -07001552 if (mTimeProvider != null) {
1553 mTimeProvider.close();
1554 mTimeProvider = null;
1555 }
Chong Zhang83ddaf62013-08-06 09:43:22 -07001556 mOnSubtitleDataListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 _release();
1558 }
1559
1560 private native void _release();
Nicolas Catania32f82772009-06-11 16:33:49 -07001561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 /**
1563 * Resets the MediaPlayer to its uninitialized state. After calling
1564 * this method, you will have to initialize it again by setting the
1565 * data source and calling prepare().
1566 */
1567 public void reset() {
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001568 mSelectedSubtitleTrackIndex = -1;
1569 synchronized(mOpenSubtitleSources) {
1570 for (final InputStream is: mOpenSubtitleSources) {
1571 try {
1572 is.close();
1573 } catch (IOException e) {
1574 }
1575 }
1576 mOpenSubtitleSources.clear();
1577 }
1578 mOutOfBandSubtitleTracks.clear();
1579 mInbandSubtitleTracks = new SubtitleTrack[0];
1580 if (mSubtitleController != null) {
1581 mSubtitleController.reset();
1582 }
Lajos Molnara67a4432013-09-06 06:30:35 -07001583 if (mTimeProvider != null) {
1584 mTimeProvider.close();
1585 mTimeProvider = null;
1586 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 stayAwake(false);
1589 _reset();
1590 // make sure none of the listeners get called anymore
Lajos Molnara67a4432013-09-06 06:30:35 -07001591 if (mEventHandler != null) {
1592 mEventHandler.removeCallbacksAndMessages(null);
1593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 private native void _reset();
Nicolas Catania32f82772009-06-11 16:33:49 -07001597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 /**
1599 * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
James Dong9d963542010-06-03 10:36:04 -07001600 * for a list of stream types. Must call this method before prepare() or
1601 * prepareAsync() in order for the target stream type to become effective
1602 * thereafter.
Nicolas Catania32f82772009-06-11 16:33:49 -07001603 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 * @param streamtype the audio stream type
1605 * @see android.media.AudioManager
1606 */
John Spurlock1af30c72014-03-10 08:33:35 -04001607 public void setAudioStreamType(int streamtype) {
1608 _setAudioStreamType(streamtype);
1609 mStreamType = streamtype;
1610 }
1611
1612 private native void _setAudioStreamType(int streamtype);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613
Jean-Michel Trivi8df982d2014-06-26 12:05:16 -07001614 // Keep KEY_PARAMETER_* in sync with include/media/mediaplayer.h
1615 private final static int KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400;
1616 /**
1617 * Sets the parameter indicated by key.
1618 * @param key key indicates the parameter to be set.
1619 * @param value value of the parameter to be set.
1620 * @return true if the parameter is set successfully, false otherwise
1621 * {@hide}
1622 */
1623 private native boolean setParameter(int key, Parcel value);
1624
1625 /**
Jean-Michel Trivi79f5cd12014-07-15 15:42:25 -07001626 * Sets the audio attributes for this MediaPlayer.
1627 * See {@link AudioAttributes} for how to build and configure an instance of this class.
1628 * You must call this method before {@link #prepare()} or {@link #prepareAsync()} in order
1629 * for the audio attributes to become effective thereafter.
Jean-Michel Trivi8df982d2014-06-26 12:05:16 -07001630 * @param attributes a non-null set of audio attributes
1631 */
1632 public void setAudioAttributes(AudioAttributes attributes) throws IllegalArgumentException {
1633 if (attributes == null) {
Jean-Michel Trivi79f5cd12014-07-15 15:42:25 -07001634 final String msg = "Cannot set AudioAttributes to null";
Jean-Michel Trivi8df982d2014-06-26 12:05:16 -07001635 throw new IllegalArgumentException(msg);
1636 }
John Spurlock7b414672014-07-18 13:02:39 -04001637 mUsage = attributes.getUsage();
John Spurlockbbfd31a2015-02-18 11:58:14 -05001638 mBypassInterruptionPolicy = (attributes.getFlags()
1639 & AudioAttributes.FLAG_BYPASS_INTERRUPTION_POLICY) != 0;
Jean-Michel Trivi8df982d2014-06-26 12:05:16 -07001640 Parcel pattributes = Parcel.obtain();
1641 attributes.writeToParcel(pattributes, AudioAttributes.FLATTEN_TAGS);
1642 setParameter(KEY_PARAMETER_AUDIO_ATTRIBUTES, pattributes);
1643 pattributes.recycle();
1644 }
1645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 /**
1647 * Sets the player to be looping or non-looping.
Nicolas Catania32f82772009-06-11 16:33:49 -07001648 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 * @param looping whether to loop or not
1650 */
1651 public native void setLooping(boolean looping);
1652
1653 /**
1654 * Checks whether the MediaPlayer is looping or non-looping.
Nicolas Catania32f82772009-06-11 16:33:49 -07001655 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 * @return true if the MediaPlayer is currently looping, false otherwise
1657 */
1658 public native boolean isLooping();
1659
1660 /**
Nicolas Catania32f82772009-06-11 16:33:49 -07001661 * Sets the volume on this player.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 * This API is recommended for balancing the output of audio streams
1663 * within an application. Unless you are writing an application to
1664 * control user settings, this API should be used in preference to
1665 * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
Glenn Kasten068225d2012-02-27 16:21:04 -08001666 * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 * UI controls should be scaled logarithmically.
1668 *
1669 * @param leftVolume left volume scalar
1670 * @param rightVolume right volume scalar
1671 */
Glenn Kasten068225d2012-02-27 16:21:04 -08001672 /*
1673 * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
1674 * The single parameter form below is preferred if the channel volumes don't need
1675 * to be set independently.
1676 */
John Spurlock1af30c72014-03-10 08:33:35 -04001677 public void setVolume(float leftVolume, float rightVolume) {
1678 if (isRestricted()) {
1679 return;
1680 }
1681 _setVolume(leftVolume, rightVolume);
1682 }
1683
1684 private native void _setVolume(float leftVolume, float rightVolume);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685
1686 /**
Glenn Kasten068225d2012-02-27 16:21:04 -08001687 * Similar, excepts sets volume of all channels to same value.
1688 * @hide
1689 */
1690 public void setVolume(float volume) {
1691 setVolume(volume, volume);
1692 }
1693
1694 /**
Eric Laurent619346f2010-06-21 09:27:30 -07001695 * Sets the audio session ID.
1696 *
Eric Laurent17cb2802010-08-03 03:50:02 -07001697 * @param sessionId the audio session ID.
Eric Laurent619346f2010-06-21 09:27:30 -07001698 * The audio session ID is a system wide unique identifier for the audio stream played by
1699 * this MediaPlayer instance.
1700 * The primary use of the audio session ID is to associate audio effects to a particular
1701 * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1702 * this effect will be applied only to the audio content of media players within the same
1703 * audio session and not to the output mix.
1704 * When created, a MediaPlayer instance automatically generates its own audio session ID.
1705 * However, it is possible to force this player to be part of an already existing audio session
1706 * by calling this method.
1707 * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1708 * @throws IllegalStateException if it is called in an invalid state
Eric Laurent619346f2010-06-21 09:27:30 -07001709 */
1710 public native void setAudioSessionId(int sessionId) throws IllegalArgumentException, IllegalStateException;
1711
1712 /**
1713 * Returns the audio session ID.
1714 *
Eric Laurent17cb2802010-08-03 03:50:02 -07001715 * @return the audio session ID. {@see #setAudioSessionId(int)}
Eric Laurent619346f2010-06-21 09:27:30 -07001716 * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
Eric Laurent619346f2010-06-21 09:27:30 -07001717 */
1718 public native int getAudioSessionId();
1719
1720 /**
Eric Laurent7070b362010-07-16 07:43:46 -07001721 * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1722 * effect which can be applied on any sound source that directs a certain amount of its
1723 * energy to this effect. This amount is defined by setAuxEffectSendLevel().
Ryan Lothian1e88cf02014-11-26 18:04:45 +00001724 * See {@link #setAuxEffectSendLevel(float)}.
Eric Laurent1a5149e2010-09-21 18:18:20 -07001725 * <p>After creating an auxiliary effect (e.g.
1726 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1727 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1728 * to attach the player to the effect.
Eric Laurent7070b362010-07-16 07:43:46 -07001729 * <p>To detach the effect from the player, call this method with a null effect id.
1730 * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1731 * methods.
Eric Laurent7070b362010-07-16 07:43:46 -07001732 * @param effectId system wide unique id of the effect to attach
Eric Laurent7070b362010-07-16 07:43:46 -07001733 */
1734 public native void attachAuxEffect(int effectId);
1735
Gloria Wangd01ec6e2011-04-25 17:28:22 -07001736
1737 /**
Ryan Lothian1e88cf02014-11-26 18:04:45 +00001738 * Sets the send level of the player to the attached auxiliary effect.
1739 * See {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
Eric Laurent7070b362010-07-16 07:43:46 -07001740 * <p>By default the send level is 0, so even if an effect is attached to the player
1741 * this method must be called for the effect to be applied.
1742 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1743 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1744 * so an appropriate conversion from linear UI input x to level is:
1745 * x == 0 -> level = 0
1746 * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1747 * @param level send level scalar
Eric Laurent7070b362010-07-16 07:43:46 -07001748 */
John Spurlock1af30c72014-03-10 08:33:35 -04001749 public void setAuxEffectSendLevel(float level) {
1750 if (isRestricted()) {
1751 return;
1752 }
1753 _setAuxEffectSendLevel(level);
1754 }
1755
1756 private native void _setAuxEffectSendLevel(float level);
Eric Laurent7070b362010-07-16 07:43:46 -07001757
Insun Kang41f3f712012-02-16 20:28:27 +09001758 /*
Nicolas Catania20cb94e2009-05-12 23:25:55 -07001759 * @param request Parcel destinated to the media player. The
1760 * Interface token must be set to the IMediaPlayer
1761 * one to be routed correctly through the system.
Nicolas Catania5d55c712009-07-09 09:21:33 -07001762 * @param reply[out] Parcel that will contain the reply.
Nicolas Catania20cb94e2009-05-12 23:25:55 -07001763 * @return The status code.
1764 */
1765 private native final int native_invoke(Parcel request, Parcel reply);
1766
Nicolas Catania5d55c712009-07-09 09:21:33 -07001767
Insun Kang41f3f712012-02-16 20:28:27 +09001768 /*
Nicolas Catania5d55c712009-07-09 09:21:33 -07001769 * @param update_only If true fetch only the set of metadata that have
1770 * changed since the last invocation of getMetadata.
1771 * The set is built using the unfiltered
1772 * notifications the native player sent to the
1773 * MediaPlayerService during that period of
1774 * time. If false, all the metadatas are considered.
1775 * @param apply_filter If true, once the metadata set has been built based on
1776 * the value update_only, the current filter is applied.
1777 * @param reply[out] On return contains the serialized
1778 * metadata. Valid only if the call was successful.
1779 * @return The status code.
1780 */
1781 private native final boolean native_getMetadata(boolean update_only,
1782 boolean apply_filter,
1783 Parcel reply);
1784
Insun Kang41f3f712012-02-16 20:28:27 +09001785 /*
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001786 * @param request Parcel with the 2 serialized lists of allowed
1787 * metadata types followed by the one to be
1788 * dropped. Each list starts with an integer
1789 * indicating the number of metadata type elements.
1790 * @return The status code.
1791 */
1792 private native final int native_setMetadataFilter(Parcel request);
1793
Marco Nelissen4935d052009-08-03 11:12:58 -07001794 private static native final void native_init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 private native final void native_setup(Object mediaplayer_this);
1796 private native final void native_finalize();
Nicolas Catania20cb94e2009-05-12 23:25:55 -07001797
Gloria Wangd211f412011-02-19 18:37:57 -08001798 /**
Insun Kang41f3f712012-02-16 20:28:27 +09001799 * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
1800 *
James Dong7a9734d2012-04-19 13:30:20 -07001801 * @see android.media.MediaPlayer#getTrackInfo
Gloria Wangc6091dd2011-05-03 15:59:03 -07001802 */
Insun Kang41f3f712012-02-16 20:28:27 +09001803 static public class TrackInfo implements Parcelable {
1804 /**
1805 * Gets the track type.
1806 * @return TrackType which indicates if the track is video, audio, timed text.
1807 */
1808 public int getTrackType() {
1809 return mTrackType;
Gloria Wangc6091dd2011-05-03 15:59:03 -07001810 }
Insun Kang41f3f712012-02-16 20:28:27 +09001811
1812 /**
1813 * Gets the language code of the track.
1814 * @return a language code in either way of ISO-639-1 or ISO-639-2.
1815 * When the language is unknown or could not be determined,
1816 * ISO-639-2 language code, "und", is returned.
1817 */
1818 public String getLanguage() {
Lajos Molnar1c56a672013-08-15 12:05:52 -07001819 String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
1820 return language == null ? "und" : language;
1821 }
1822
1823 /**
1824 * Gets the {@link MediaFormat} of the track. If the format is
1825 * unknown or could not be determined, null is returned.
1826 */
1827 public MediaFormat getFormat() {
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001828 if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
1829 || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
Lajos Molnar1c56a672013-08-15 12:05:52 -07001830 return mFormat;
1831 }
1832 return null;
Insun Kang41f3f712012-02-16 20:28:27 +09001833 }
1834
1835 public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
1836 public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
1837 public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
1838 public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
Chong Zhang83ddaf62013-08-06 09:43:22 -07001839 public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
Robert Shihac033f02015-04-10 11:15:02 -07001840 public static final int MEDIA_TRACK_TYPE_METADATA = 5;
Insun Kang41f3f712012-02-16 20:28:27 +09001841
1842 final int mTrackType;
Lajos Molnar1c56a672013-08-15 12:05:52 -07001843 final MediaFormat mFormat;
Insun Kang41f3f712012-02-16 20:28:27 +09001844
1845 TrackInfo(Parcel in) {
1846 mTrackType = in.readInt();
Lajos Molnar1c56a672013-08-15 12:05:52 -07001847 // TODO: parcel in the full MediaFormat
1848 String language = in.readString();
1849
1850 if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1851 mFormat = MediaFormat.createSubtitleFormat(
1852 MEDIA_MIMETYPE_TEXT_SUBRIP, language);
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001853 } else if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
Chong Zhang079fa962014-06-11 15:09:13 -07001854 String mime = in.readString();
1855 mFormat = MediaFormat.createSubtitleFormat(mime, language);
Lajos Molnard486f962013-09-11 16:26:18 -07001856 mFormat.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.readInt());
1857 mFormat.setInteger(MediaFormat.KEY_IS_DEFAULT, in.readInt());
1858 mFormat.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.readInt());
Lajos Molnar1c56a672013-08-15 12:05:52 -07001859 } else {
1860 mFormat = new MediaFormat();
1861 mFormat.setString(MediaFormat.KEY_LANGUAGE, language);
1862 }
Insun Kang41f3f712012-02-16 20:28:27 +09001863 }
1864
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001865 /** @hide */
1866 TrackInfo(int type, MediaFormat format) {
1867 mTrackType = type;
1868 mFormat = format;
1869 }
1870
James Dong7a9734d2012-04-19 13:30:20 -07001871 /**
1872 * {@inheritDoc}
Insun Kang41f3f712012-02-16 20:28:27 +09001873 */
1874 @Override
1875 public int describeContents() {
1876 return 0;
1877 }
1878
James Dong7a9734d2012-04-19 13:30:20 -07001879 /**
1880 * {@inheritDoc}
Insun Kang41f3f712012-02-16 20:28:27 +09001881 */
1882 @Override
1883 public void writeToParcel(Parcel dest, int flags) {
1884 dest.writeInt(mTrackType);
Lajos Molnar1c56a672013-08-15 12:05:52 -07001885 dest.writeString(getLanguage());
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001886
1887 if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
Chong Zhang079fa962014-06-11 15:09:13 -07001888 dest.writeString(mFormat.getString(MediaFormat.KEY_MIME));
Lajos Molnard486f962013-09-11 16:26:18 -07001889 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_AUTOSELECT));
1890 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_DEFAULT));
1891 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE));
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001892 }
Insun Kang41f3f712012-02-16 20:28:27 +09001893 }
1894
Chong Zhang079fa962014-06-11 15:09:13 -07001895 @Override
1896 public String toString() {
1897 StringBuilder out = new StringBuilder(128);
1898 out.append(getClass().getName());
1899 out.append('{');
1900 switch (mTrackType) {
1901 case MEDIA_TRACK_TYPE_VIDEO:
1902 out.append("VIDEO");
1903 break;
1904 case MEDIA_TRACK_TYPE_AUDIO:
1905 out.append("AUDIO");
1906 break;
1907 case MEDIA_TRACK_TYPE_TIMEDTEXT:
1908 out.append("TIMEDTEXT");
1909 break;
1910 case MEDIA_TRACK_TYPE_SUBTITLE:
1911 out.append("SUBTITLE");
1912 break;
1913 default:
1914 out.append("UNKNOWN");
1915 break;
1916 }
1917 out.append(", " + mFormat.toString());
1918 out.append("}");
1919 return out.toString();
1920 }
1921
Insun Kang41f3f712012-02-16 20:28:27 +09001922 /**
1923 * Used to read a TrackInfo from a Parcel.
1924 */
1925 static final Parcelable.Creator<TrackInfo> CREATOR
1926 = new Parcelable.Creator<TrackInfo>() {
1927 @Override
1928 public TrackInfo createFromParcel(Parcel in) {
1929 return new TrackInfo(in);
1930 }
1931
1932 @Override
1933 public TrackInfo[] newArray(int size) {
1934 return new TrackInfo[size];
1935 }
1936 };
1937
1938 };
1939
1940 /**
1941 * Returns an array of track information.
1942 *
James Dong831f0a92012-04-18 18:12:12 -07001943 * @return Array of track info. The total number of tracks is the array length.
James Dong7a9734d2012-04-19 13:30:20 -07001944 * Must be called again if an external timed text source has been added after any of the
1945 * addTimedTextSource methods are called.
1946 * @throws IllegalStateException if it is called in an invalid state.
Insun Kang41f3f712012-02-16 20:28:27 +09001947 */
James Dong7a9734d2012-04-19 13:30:20 -07001948 public TrackInfo[] getTrackInfo() throws IllegalStateException {
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001949 TrackInfo trackInfo[] = getInbandTrackInfo();
1950 // add out-of-band tracks
1951 TrackInfo allTrackInfo[] = new TrackInfo[trackInfo.length + mOutOfBandSubtitleTracks.size()];
1952 System.arraycopy(trackInfo, 0, allTrackInfo, 0, trackInfo.length);
1953 int i = trackInfo.length;
1954 for (SubtitleTrack track: mOutOfBandSubtitleTracks) {
Robert Shih3cdf7c52014-07-23 17:18:46 -07001955 int type = track.isTimedText()
1956 ? TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT
1957 : TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE;
1958 allTrackInfo[i] = new TrackInfo(type, track.getFormat());
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001959 ++i;
1960 }
1961 return allTrackInfo;
1962 }
1963
1964 private TrackInfo[] getInbandTrackInfo() throws IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09001965 Parcel request = Parcel.obtain();
1966 Parcel reply = Parcel.obtain();
Insun Kangbe0ea962012-05-04 20:52:57 +09001967 try {
1968 request.writeInterfaceToken(IMEDIA_PLAYER);
1969 request.writeInt(INVOKE_ID_GET_TRACK_INFO);
1970 invoke(request, reply);
1971 TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
1972 return trackInfo;
1973 } finally {
1974 request.recycle();
1975 reply.recycle();
1976 }
Insun Kang41f3f712012-02-16 20:28:27 +09001977 }
1978
James Dong831f0a92012-04-18 18:12:12 -07001979 /* Do not change these values without updating their counterparts
1980 * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
1981 */
1982 /**
James Dong7a9734d2012-04-19 13:30:20 -07001983 * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
James Dong831f0a92012-04-18 18:12:12 -07001984 */
1985 public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
1986
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001987 /**
1988 * MIME type for WebVTT subtitle data.
1989 * @hide
1990 */
1991 public static final String MEDIA_MIMETYPE_TEXT_VTT = "text/vtt";
1992
Chong Zhangbdfd9102014-06-11 15:10:23 -07001993 /**
1994 * MIME type for CEA-608 closed caption data.
1995 * @hide
1996 */
1997 public static final String MEDIA_MIMETYPE_TEXT_CEA_608 = "text/cea-608";
1998
Insun Kang41f3f712012-02-16 20:28:27 +09001999 /*
2000 * A helper function to check if the mime type is supported by media framework.
2001 */
James Dong831f0a92012-04-18 18:12:12 -07002002 private static boolean availableMimeTypeForExternalSource(String mimeType) {
Robert Shih3cdf7c52014-07-23 17:18:46 -07002003 if (MEDIA_MIMETYPE_TEXT_SUBRIP.equals(mimeType)) {
Insun Kang41f3f712012-02-16 20:28:27 +09002004 return true;
2005 }
2006 return false;
2007 }
2008
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002009 private SubtitleController mSubtitleController;
2010
2011 /** @hide */
2012 public void setSubtitleAnchor(
2013 SubtitleController controller,
2014 SubtitleController.Anchor anchor) {
2015 // TODO: create SubtitleController in MediaPlayer
2016 mSubtitleController = controller;
2017 mSubtitleController.setAnchor(anchor);
2018 }
2019
Robert Shih8c4d53c2014-09-05 13:33:31 -07002020 private final Object mInbandSubtitleLock = new Object();
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002021 private SubtitleTrack[] mInbandSubtitleTracks;
2022 private int mSelectedSubtitleTrackIndex = -1;
2023 private Vector<SubtitleTrack> mOutOfBandSubtitleTracks;
2024 private Vector<InputStream> mOpenSubtitleSources;
2025
2026 private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() {
2027 @Override
2028 public void onSubtitleData(MediaPlayer mp, SubtitleData data) {
2029 int index = data.getTrackIndex();
2030 if (index >= mInbandSubtitleTracks.length) {
2031 return;
2032 }
2033 SubtitleTrack track = mInbandSubtitleTracks[index];
2034 if (track != null) {
Robert Shih38c209b2014-06-10 17:28:37 -07002035 track.onData(data);
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002036 }
2037 }
2038 };
2039
2040 /** @hide */
2041 @Override
2042 public void onSubtitleTrackSelected(SubtitleTrack track) {
2043 if (mSelectedSubtitleTrackIndex >= 0) {
Lajos Molnard486f962013-09-11 16:26:18 -07002044 try {
2045 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, false);
2046 } catch (IllegalStateException e) {
2047 }
2048 mSelectedSubtitleTrackIndex = -1;
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002049 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002050 setOnSubtitleDataListener(null);
Lajos Molnar29f51832013-09-20 08:45:31 -07002051 if (track == null) {
2052 return;
2053 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002054 for (int i = 0; i < mInbandSubtitleTracks.length; i++) {
2055 if (mInbandSubtitleTracks[i] == track) {
2056 Log.v(TAG, "Selecting subtitle track " + i);
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002057 mSelectedSubtitleTrackIndex = i;
Lajos Molnard486f962013-09-11 16:26:18 -07002058 try {
2059 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true);
2060 } catch (IllegalStateException e) {
2061 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002062 setOnSubtitleDataListener(mSubtitleDataListener);
2063 break;
2064 }
2065 }
2066 // no need to select out-of-band tracks
2067 }
2068
2069 /** @hide */
2070 public void addSubtitleSource(InputStream is, MediaFormat format)
2071 throws IllegalStateException
2072 {
2073 final InputStream fIs = is;
2074 final MediaFormat fFormat = format;
2075
2076 // Ensure all input streams are closed. It is also a handy
2077 // way to implement timeouts in the future.
2078 synchronized(mOpenSubtitleSources) {
2079 mOpenSubtitleSources.add(is);
2080 }
2081
2082 // process each subtitle in its own thread
2083 final HandlerThread thread = new HandlerThread("SubtitleReadThread",
2084 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
2085 thread.start();
2086 Handler handler = new Handler(thread.getLooper());
2087 handler.post(new Runnable() {
2088 private int addTrack() {
2089 if (fIs == null || mSubtitleController == null) {
2090 return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
2091 }
2092
2093 SubtitleTrack track = mSubtitleController.addTrack(fFormat);
2094 if (track == null) {
2095 return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
2096 }
2097
2098 // TODO: do the conversion in the subtitle track
2099 Scanner scanner = new Scanner(fIs, "UTF-8");
2100 String contents = scanner.useDelimiter("\\A").next();
2101 synchronized(mOpenSubtitleSources) {
2102 mOpenSubtitleSources.remove(fIs);
2103 }
2104 scanner.close();
2105 mOutOfBandSubtitleTracks.add(track);
Chong Zhang079fa962014-06-11 15:09:13 -07002106 track.onData(contents.getBytes(), true /* eos */, ~0 /* runID: keep forever */);
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002107 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
2108 }
2109
2110 public void run() {
2111 int res = addTrack();
2112 if (mEventHandler != null) {
2113 Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
2114 mEventHandler.sendMessage(m);
2115 }
2116 thread.getLooper().quitSafely();
2117 }
2118 });
2119 }
2120
2121 private void scanInternalSubtitleTracks() {
2122 if (mSubtitleController == null) {
2123 Log.e(TAG, "Should have subtitle controller already set");
2124 return;
2125 }
2126
2127 TrackInfo[] tracks = getInbandTrackInfo();
Robert Shih8c4d53c2014-09-05 13:33:31 -07002128 synchronized (mInbandSubtitleLock) {
2129 SubtitleTrack[] inbandTracks = new SubtitleTrack[tracks.length];
2130 for (int i=0; i < tracks.length; i++) {
2131 if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
2132 if (i < mInbandSubtitleTracks.length) {
2133 inbandTracks[i] = mInbandSubtitleTracks[i];
2134 } else {
2135 SubtitleTrack track = mSubtitleController.addTrack(
2136 tracks[i].getFormat());
2137 inbandTracks[i] = track;
2138 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002139 }
2140 }
Robert Shih8c4d53c2014-09-05 13:33:31 -07002141 mInbandSubtitleTracks = inbandTracks;
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002142 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002143 mSubtitleController.selectDefaultTrack();
2144 }
2145
Insun Kang41f3f712012-02-16 20:28:27 +09002146 /* TODO: Limit the total number of external timed text source to a reasonable number.
2147 */
2148 /**
James Dong7a9734d2012-04-19 13:30:20 -07002149 * Adds an external timed text source file.
Insun Kang41f3f712012-02-16 20:28:27 +09002150 *
2151 * Currently supported format is SubRip with the file extension .srt, case insensitive.
James Dong7a9734d2012-04-19 13:30:20 -07002152 * Note that a single external timed text source may contain multiple tracks in it.
Insun Kang41f3f712012-02-16 20:28:27 +09002153 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
2154 * additional tracks become available after this method call.
2155 *
James Dong7a9734d2012-04-19 13:30:20 -07002156 * @param path The file path of external timed text source file.
James Dong831f0a92012-04-18 18:12:12 -07002157 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2158 * @throws IOException if the file cannot be accessed or is corrupted.
2159 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07002160 * @throws IllegalStateException if called in an invalid state.
Insun Kang41f3f712012-02-16 20:28:27 +09002161 */
James Dong7a9734d2012-04-19 13:30:20 -07002162 public void addTimedTextSource(String path, String mimeType)
2163 throws IOException, IllegalArgumentException, IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09002164 if (!availableMimeTypeForExternalSource(mimeType)) {
James Dong7a9734d2012-04-19 13:30:20 -07002165 final String msg = "Illegal mimeType for timed text source: " + mimeType;
James Dongc4c02842012-04-12 19:49:02 -07002166 throw new IllegalArgumentException(msg);
Insun Kang41f3f712012-02-16 20:28:27 +09002167 }
2168
James Dongc4c02842012-04-12 19:49:02 -07002169 File file = new File(path);
2170 if (file.exists()) {
2171 FileInputStream is = new FileInputStream(file);
2172 FileDescriptor fd = is.getFD();
James Dong7a9734d2012-04-19 13:30:20 -07002173 addTimedTextSource(fd, mimeType);
James Dongc4c02842012-04-12 19:49:02 -07002174 is.close();
2175 } else {
2176 // We do not support the case where the path is not a file.
2177 throw new IOException(path);
2178 }
Gloria Wangc6091dd2011-05-03 15:59:03 -07002179 }
2180
2181 /**
James Dong7a9734d2012-04-19 13:30:20 -07002182 * Adds an external timed text source file (Uri).
Insun Kang41f3f712012-02-16 20:28:27 +09002183 *
2184 * Currently supported format is SubRip with the file extension .srt, case insensitive.
James Dong7a9734d2012-04-19 13:30:20 -07002185 * Note that a single external timed text source may contain multiple tracks in it.
Insun Kang41f3f712012-02-16 20:28:27 +09002186 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
2187 * additional tracks become available after this method call.
2188 *
2189 * @param context the Context to use when resolving the Uri
2190 * @param uri the Content URI of the data you want to play
James Dong831f0a92012-04-18 18:12:12 -07002191 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2192 * @throws IOException if the file cannot be accessed or is corrupted.
2193 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07002194 * @throws IllegalStateException if called in an invalid state.
Gloria Wangc6091dd2011-05-03 15:59:03 -07002195 */
James Dong7a9734d2012-04-19 13:30:20 -07002196 public void addTimedTextSource(Context context, Uri uri, String mimeType)
2197 throws IOException, IllegalArgumentException, IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09002198 String scheme = uri.getScheme();
2199 if(scheme == null || scheme.equals("file")) {
James Dong7a9734d2012-04-19 13:30:20 -07002200 addTimedTextSource(uri.getPath(), mimeType);
Insun Kang41f3f712012-02-16 20:28:27 +09002201 return;
2202 }
2203
2204 AssetFileDescriptor fd = null;
2205 try {
2206 ContentResolver resolver = context.getContentResolver();
2207 fd = resolver.openAssetFileDescriptor(uri, "r");
2208 if (fd == null) {
2209 return;
2210 }
James Dong7a9734d2012-04-19 13:30:20 -07002211 addTimedTextSource(fd.getFileDescriptor(), mimeType);
Insun Kang41f3f712012-02-16 20:28:27 +09002212 return;
2213 } catch (SecurityException ex) {
2214 } catch (IOException ex) {
2215 } finally {
2216 if (fd != null) {
2217 fd.close();
2218 }
2219 }
Insun Kang41f3f712012-02-16 20:28:27 +09002220 }
2221
Insun Kang41f3f712012-02-16 20:28:27 +09002222 /**
James Dong7a9734d2012-04-19 13:30:20 -07002223 * Adds an external timed text source file (FileDescriptor).
2224 *
Insun Kang41f3f712012-02-16 20:28:27 +09002225 * It is the caller's responsibility to close the file descriptor.
2226 * It is safe to do so as soon as this call returns.
2227 *
James Dong7a9734d2012-04-19 13:30:20 -07002228 * Currently supported format is SubRip. Note that a single external timed text source may
2229 * contain multiple tracks in it. One can find the total number of available tracks
2230 * using {@link #getTrackInfo()} to see what additional tracks become available
2231 * after this method call.
Insun Kang41f3f712012-02-16 20:28:27 +09002232 *
2233 * @param fd the FileDescriptor for the file you want to play
James Dong831f0a92012-04-18 18:12:12 -07002234 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2235 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07002236 * @throws IllegalStateException if called in an invalid state.
Insun Kang41f3f712012-02-16 20:28:27 +09002237 */
James Dong7a9734d2012-04-19 13:30:20 -07002238 public void addTimedTextSource(FileDescriptor fd, String mimeType)
2239 throws IllegalArgumentException, IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09002240 // intentionally less than LONG_MAX
James Dong7a9734d2012-04-19 13:30:20 -07002241 addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
Gloria Wangc6091dd2011-05-03 15:59:03 -07002242 }
2243
2244 /**
Insun Kang41f3f712012-02-16 20:28:27 +09002245 * Adds an external timed text file (FileDescriptor).
James Dong7a9734d2012-04-19 13:30:20 -07002246 *
Insun Kang41f3f712012-02-16 20:28:27 +09002247 * It is the caller's responsibility to close the file descriptor.
2248 * It is safe to do so as soon as this call returns.
2249 *
James Dong7a9734d2012-04-19 13:30:20 -07002250 * Currently supported format is SubRip. Note that a single external timed text source may
2251 * contain multiple tracks in it. One can find the total number of available tracks
2252 * using {@link #getTrackInfo()} to see what additional tracks become available
2253 * after this method call.
Insun Kang41f3f712012-02-16 20:28:27 +09002254 *
2255 * @param fd the FileDescriptor for the file you want to play
2256 * @param offset the offset into the file where the data to be played starts, in bytes
2257 * @param length the length in bytes of the data to be played
Ying Wang546f3bf2014-07-29 16:23:15 -07002258 * @param mime The mime type of the file. Must be one of the mime types listed above.
James Dong831f0a92012-04-18 18:12:12 -07002259 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07002260 * @throws IllegalStateException if called in an invalid state.
Gloria Wangc6091dd2011-05-03 15:59:03 -07002261 */
Robert Shih3cdf7c52014-07-23 17:18:46 -07002262 public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mime)
James Dong7a9734d2012-04-19 13:30:20 -07002263 throws IllegalArgumentException, IllegalStateException {
Robert Shih3cdf7c52014-07-23 17:18:46 -07002264 if (!availableMimeTypeForExternalSource(mime)) {
2265 throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mime);
Insun Kang41f3f712012-02-16 20:28:27 +09002266 }
James Dongc4c02842012-04-12 19:49:02 -07002267
Robert Shih3cdf7c52014-07-23 17:18:46 -07002268 FileDescriptor fd2;
Insun Kangbe0ea962012-05-04 20:52:57 +09002269 try {
Robert Shih3cdf7c52014-07-23 17:18:46 -07002270 fd2 = Libcore.os.dup(fd);
2271 } catch (ErrnoException ex) {
2272 Log.e(TAG, ex.getMessage(), ex);
2273 throw new RuntimeException(ex);
Insun Kangbe0ea962012-05-04 20:52:57 +09002274 }
Robert Shih3cdf7c52014-07-23 17:18:46 -07002275
2276 final MediaFormat fFormat = new MediaFormat();
2277 fFormat.setString(MediaFormat.KEY_MIME, mime);
2278 fFormat.setInteger(MediaFormat.KEY_IS_TIMED_TEXT, 1);
2279
2280 Context context = ActivityThread.currentApplication();
2281 // A MediaPlayer created by a VideoView should already have its mSubtitleController set.
2282 if (mSubtitleController == null) {
2283 mSubtitleController = new SubtitleController(context, mTimeProvider, this);
2284 mSubtitleController.setAnchor(new Anchor() {
2285 @Override
2286 public void setSubtitleWidget(RenderingWidget subtitleWidget) {
2287 }
2288
2289 @Override
2290 public Looper getSubtitleLooper() {
2291 return Looper.getMainLooper();
2292 }
2293 });
2294 }
2295
2296 if (!mSubtitleController.hasRendererFor(fFormat)) {
2297 // test and add not atomic
2298 mSubtitleController.registerRenderer(new SRTRenderer(context, mEventHandler));
2299 }
2300 final SubtitleTrack track = mSubtitleController.addTrack(fFormat);
2301 mOutOfBandSubtitleTracks.add(track);
2302
2303 final FileDescriptor fd3 = fd2;
2304 final long offset2 = offset;
2305 final long length2 = length;
2306 final HandlerThread thread = new HandlerThread(
2307 "TimedTextReadThread",
2308 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
2309 thread.start();
2310 Handler handler = new Handler(thread.getLooper());
2311 handler.post(new Runnable() {
2312 private int addTrack() {
2313 InputStream is = null;
2314 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
2315 try {
2316 Libcore.os.lseek(fd3, offset2, OsConstants.SEEK_SET);
2317 byte[] buffer = new byte[4096];
Robert Shih8c4d53c2014-09-05 13:33:31 -07002318 for (long total = 0; total < length2;) {
2319 int bytesToRead = (int) Math.min(buffer.length, length2 - total);
2320 int bytes = IoBridge.read(fd3, buffer, 0, bytesToRead);
Robert Shih3cdf7c52014-07-23 17:18:46 -07002321 if (bytes < 0) {
2322 break;
2323 } else {
2324 bos.write(buffer, 0, bytes);
2325 total += bytes;
2326 }
2327 }
2328 track.onData(bos.toByteArray(), true /* eos */, ~0 /* runID: keep forever */);
2329 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
2330 } catch (Exception e) {
2331 Log.e(TAG, e.getMessage(), e);
2332 return MEDIA_INFO_TIMED_TEXT_ERROR;
2333 } finally {
2334 if (is != null) {
2335 try {
2336 is.close();
2337 } catch (IOException e) {
2338 Log.e(TAG, e.getMessage(), e);
2339 }
2340 }
2341 }
2342 }
2343
2344 public void run() {
2345 int res = addTrack();
2346 if (mEventHandler != null) {
2347 Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
2348 mEventHandler.sendMessage(m);
2349 }
2350 thread.getLooper().quitSafely();
2351 }
2352 });
Insun Kang41f3f712012-02-16 20:28:27 +09002353 }
2354
2355 /**
Robert Shih464da702014-05-29 10:54:32 -07002356 * Returns the index of the audio, video, or subtitle track currently selected for playback,
2357 * The return value is an index into the array returned by {@link #getTrackInfo()}, and can
2358 * be used in calls to {@link #selectTrack(int)} or {@link #deselectTrack(int)}.
2359 *
2360 * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
2361 * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
2362 * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
2363 * @return index of the audio, video, or subtitle track currently selected for playback;
2364 * a negative integer is returned when there is no selected track for {@code trackType} or
2365 * when {@code trackType} is not one of audio, video, or subtitle.
2366 * @throws IllegalStateException if called after {@link #release()}
2367 *
Ryan Lothian1e88cf02014-11-26 18:04:45 +00002368 * @see #getTrackInfo()
2369 * @see #selectTrack(int)
2370 * @see #deselectTrack(int)
Robert Shih464da702014-05-29 10:54:32 -07002371 */
2372 public int getSelectedTrack(int trackType) throws IllegalStateException {
2373 if (trackType == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE && mSubtitleController != null) {
2374 SubtitleTrack subtitleTrack = mSubtitleController.getSelectedTrack();
2375 if (subtitleTrack != null) {
2376 int index = mOutOfBandSubtitleTracks.indexOf(subtitleTrack);
2377 if (index >= 0) {
2378 return mInbandSubtitleTracks.length + index;
2379 }
2380 }
2381 }
2382
2383 Parcel request = Parcel.obtain();
2384 Parcel reply = Parcel.obtain();
2385 try {
2386 request.writeInterfaceToken(IMEDIA_PLAYER);
2387 request.writeInt(INVOKE_ID_GET_SELECTED_TRACK);
2388 request.writeInt(trackType);
2389 invoke(request, reply);
2390 int selectedTrack = reply.readInt();
2391 return selectedTrack;
2392 } finally {
2393 request.recycle();
2394 reply.recycle();
2395 }
2396 }
2397
2398 /**
Insun Kang41f3f712012-02-16 20:28:27 +09002399 * Selects a track.
2400 * <p>
James Dong831f0a92012-04-18 18:12:12 -07002401 * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
2402 * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
Insun Kang41f3f712012-02-16 20:28:27 +09002403 * If a MediaPlayer is not in Started state, it just marks the track to be played.
2404 * </p>
2405 * <p>
2406 * In any valid state, if it is called multiple times on the same type of track (ie. Video,
2407 * Audio, Timed Text), the most recent one will be chosen.
2408 * </p>
2409 * <p>
James Dong831f0a92012-04-18 18:12:12 -07002410 * The first audio and video tracks are selected by default if available, even though
2411 * this method is not called. However, no timed text track will be selected until
2412 * this function is called.
Insun Kang41f3f712012-02-16 20:28:27 +09002413 * </p>
James Dong831f0a92012-04-18 18:12:12 -07002414 * <p>
2415 * Currently, only timed text tracks or audio tracks can be selected via this method.
2416 * In addition, the support for selecting an audio track at runtime is pretty limited
2417 * in that an audio track can only be selected in the <em>Prepared</em> state.
2418 * </p>
2419 * @param index the index of the track to be selected. The valid range of the index
2420 * is 0..total number of track - 1. The total number of tracks as well as the type of
2421 * each individual track can be found by calling {@link #getTrackInfo()} method.
James Dong7a9734d2012-04-19 13:30:20 -07002422 * @throws IllegalStateException if called in an invalid state.
2423 *
2424 * @see android.media.MediaPlayer#getTrackInfo
Insun Kang41f3f712012-02-16 20:28:27 +09002425 */
James Dong7a9734d2012-04-19 13:30:20 -07002426 public void selectTrack(int index) throws IllegalStateException {
2427 selectOrDeselectTrack(index, true /* select */);
Insun Kang41f3f712012-02-16 20:28:27 +09002428 }
2429
2430 /**
James Dong7a9734d2012-04-19 13:30:20 -07002431 * Deselect a track.
James Dong831f0a92012-04-18 18:12:12 -07002432 * <p>
2433 * Currently, the track must be a timed text track and no audio or video tracks can be
James Dong7a9734d2012-04-19 13:30:20 -07002434 * deselected. If the timed text track identified by index has not been
James Dong831f0a92012-04-18 18:12:12 -07002435 * selected before, it throws an exception.
2436 * </p>
James Dong7a9734d2012-04-19 13:30:20 -07002437 * @param index the index of the track to be deselected. The valid range of the index
James Dong831f0a92012-04-18 18:12:12 -07002438 * is 0..total number of tracks - 1. The total number of tracks as well as the type of
2439 * each individual track can be found by calling {@link #getTrackInfo()} method.
James Dong7a9734d2012-04-19 13:30:20 -07002440 * @throws IllegalStateException if called in an invalid state.
James Dong831f0a92012-04-18 18:12:12 -07002441 *
James Dong7a9734d2012-04-19 13:30:20 -07002442 * @see android.media.MediaPlayer#getTrackInfo
Insun Kang41f3f712012-02-16 20:28:27 +09002443 */
James Dong7a9734d2012-04-19 13:30:20 -07002444 public void deselectTrack(int index) throws IllegalStateException {
2445 selectOrDeselectTrack(index, false /* select */);
James Dong831f0a92012-04-18 18:12:12 -07002446 }
2447
James Dong7a9734d2012-04-19 13:30:20 -07002448 private void selectOrDeselectTrack(int index, boolean select)
2449 throws IllegalStateException {
Lajos Molnard486f962013-09-11 16:26:18 -07002450 // handle subtitle track through subtitle controller
2451 SubtitleTrack track = null;
Robert Shih8c4d53c2014-09-05 13:33:31 -07002452 synchronized (mInbandSubtitleLock) {
2453 if (mInbandSubtitleTracks.length == 0) {
2454 TrackInfo[] tracks = getInbandTrackInfo();
2455 mInbandSubtitleTracks = new SubtitleTrack[tracks.length];
2456 for (int i=0; i < tracks.length; i++) {
2457 if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
2458 mInbandSubtitleTracks[i] = mSubtitleController.addTrack(tracks[i].getFormat());
2459 }
2460 }
2461 }
2462 }
2463
Lajos Molnard486f962013-09-11 16:26:18 -07002464 if (index < mInbandSubtitleTracks.length) {
2465 track = mInbandSubtitleTracks[index];
2466 } else if (index < mInbandSubtitleTracks.length + mOutOfBandSubtitleTracks.size()) {
2467 track = mOutOfBandSubtitleTracks.get(index - mInbandSubtitleTracks.length);
2468 }
2469
2470 if (mSubtitleController != null && track != null) {
2471 if (select) {
Robert Shih3cdf7c52014-07-23 17:18:46 -07002472 if (track.isTimedText()) {
2473 int ttIndex = getSelectedTrack(TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT);
2474 if (ttIndex >= 0 && ttIndex < mInbandSubtitleTracks.length) {
2475 // deselect inband counterpart
2476 selectOrDeselectInbandTrack(ttIndex, false);
2477 }
2478 }
Lajos Molnard486f962013-09-11 16:26:18 -07002479 mSubtitleController.selectTrack(track);
2480 } else if (mSubtitleController.getSelectedTrack() == track) {
2481 mSubtitleController.selectTrack(null);
2482 } else {
2483 Log.w(TAG, "trying to deselect track that was not selected");
2484 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002485 return;
2486 }
2487
Lajos Molnard486f962013-09-11 16:26:18 -07002488 selectOrDeselectInbandTrack(index, select);
2489 }
2490
2491 private void selectOrDeselectInbandTrack(int index, boolean select)
2492 throws IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09002493 Parcel request = Parcel.obtain();
2494 Parcel reply = Parcel.obtain();
Insun Kangbe0ea962012-05-04 20:52:57 +09002495 try {
2496 request.writeInterfaceToken(IMEDIA_PLAYER);
2497 request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
2498 request.writeInt(index);
2499 invoke(request, reply);
2500 } finally {
2501 request.recycle();
2502 reply.recycle();
2503 }
Gloria Wangc6091dd2011-05-03 15:59:03 -07002504 }
2505
James Dong831f0a92012-04-18 18:12:12 -07002506
Gloria Wangc6091dd2011-05-03 15:59:03 -07002507 /**
Gloria Wangd211f412011-02-19 18:37:57 -08002508 * @param reply Parcel with audio/video duration info for battery
2509 tracking usage
2510 * @return The status code.
2511 * {@hide}
2512 */
2513 public native static int native_pullBatteryData(Parcel reply);
2514
John Grossman720aa282012-02-22 15:38:35 -08002515 /**
2516 * Sets the target UDP re-transmit endpoint for the low level player.
2517 * Generally, the address portion of the endpoint is an IP multicast
2518 * address, although a unicast address would be equally valid. When a valid
2519 * retransmit endpoint has been set, the media player will not decode and
2520 * render the media presentation locally. Instead, the player will attempt
2521 * to re-multiplex its media data using the Android@Home RTP profile and
2522 * re-transmit to the target endpoint. Receiver devices (which may be
2523 * either the same as the transmitting device or different devices) may
2524 * instantiate, prepare, and start a receiver player using a setDataSource
2525 * URL of the form...
2526 *
2527 * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
2528 *
2529 * to receive, decode and render the re-transmitted content.
2530 *
2531 * setRetransmitEndpoint may only be called before setDataSource has been
2532 * called; while the player is in the Idle state.
2533 *
2534 * @param endpoint the address and UDP port of the re-transmission target or
2535 * null if no re-transmission is to be performed.
2536 * @throws IllegalStateException if it is called in an invalid state
2537 * @throws IllegalArgumentException if the retransmit endpoint is supplied,
2538 * but invalid.
2539 *
2540 * {@hide} pending API council
2541 */
2542 public void setRetransmitEndpoint(InetSocketAddress endpoint)
2543 throws IllegalStateException, IllegalArgumentException
2544 {
2545 String addrString = null;
2546 int port = 0;
2547
2548 if (null != endpoint) {
2549 addrString = endpoint.getAddress().getHostAddress();
2550 port = endpoint.getPort();
2551 }
2552
2553 int ret = native_setRetransmitEndpoint(addrString, port);
2554 if (ret != 0) {
2555 throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
2556 }
2557 }
2558
2559 private native final int native_setRetransmitEndpoint(String addrString, int port);
2560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 @Override
2562 protected void finalize() { native_finalize(); }
2563
2564 /* Do not change these values without updating their counterparts
2565 * in include/media/mediaplayer.h!
2566 */
2567 private static final int MEDIA_NOP = 0; // interface test message
2568 private static final int MEDIA_PREPARED = 1;
2569 private static final int MEDIA_PLAYBACK_COMPLETE = 2;
2570 private static final int MEDIA_BUFFERING_UPDATE = 3;
2571 private static final int MEDIA_SEEK_COMPLETE = 4;
2572 private static final int MEDIA_SET_VIDEO_SIZE = 5;
Lajos Molnar3d998562013-08-15 17:05:05 -07002573 private static final int MEDIA_STARTED = 6;
2574 private static final int MEDIA_PAUSED = 7;
2575 private static final int MEDIA_STOPPED = 8;
Lajos Molnard58b1222013-09-24 18:04:23 -07002576 private static final int MEDIA_SKIPPED = 9;
Gloria Wang162ee492011-04-11 17:23:27 -07002577 private static final int MEDIA_TIMED_TEXT = 99;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 private static final int MEDIA_ERROR = 100;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002579 private static final int MEDIA_INFO = 200;
Chong Zhang83ddaf62013-08-06 09:43:22 -07002580 private static final int MEDIA_SUBTITLE_DATA = 201;
Robert Shihac033f02015-04-10 11:15:02 -07002581 private static final int MEDIA_META_DATA = 202;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582
Lajos Molnar3d998562013-08-15 17:05:05 -07002583 private TimeProvider mTimeProvider;
2584
2585 /** @hide */
2586 public MediaTimeProvider getMediaTimeProvider() {
Lajos Molnara67a4432013-09-06 06:30:35 -07002587 if (mTimeProvider == null) {
2588 mTimeProvider = new TimeProvider(this);
2589 }
Lajos Molnar3d998562013-08-15 17:05:05 -07002590 return mTimeProvider;
2591 }
2592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 private class EventHandler extends Handler
2594 {
2595 private MediaPlayer mMediaPlayer;
2596
2597 public EventHandler(MediaPlayer mp, Looper looper) {
2598 super(looper);
2599 mMediaPlayer = mp;
2600 }
2601
2602 @Override
2603 public void handleMessage(Message msg) {
2604 if (mMediaPlayer.mNativeContext == 0) {
2605 Log.w(TAG, "mediaplayer went away with unhandled events");
2606 return;
2607 }
2608 switch(msg.what) {
2609 case MEDIA_PREPARED:
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002610 scanInternalSubtitleTracks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 if (mOnPreparedListener != null)
2612 mOnPreparedListener.onPrepared(mMediaPlayer);
2613 return;
2614
2615 case MEDIA_PLAYBACK_COMPLETE:
2616 if (mOnCompletionListener != null)
2617 mOnCompletionListener.onCompletion(mMediaPlayer);
2618 stayAwake(false);
2619 return;
2620
Lajos Molnar3d998562013-08-15 17:05:05 -07002621 case MEDIA_STOPPED:
Wei Jiaaf2d2ac2015-03-30 11:16:29 -07002622 {
2623 TimeProvider timeProvider = mTimeProvider;
2624 if (timeProvider != null) {
2625 timeProvider.onStopped();
2626 }
Lajos Molnar3d998562013-08-15 17:05:05 -07002627 }
2628 break;
2629
2630 case MEDIA_STARTED:
2631 case MEDIA_PAUSED:
Wei Jiaaf2d2ac2015-03-30 11:16:29 -07002632 {
2633 TimeProvider timeProvider = mTimeProvider;
2634 if (timeProvider != null) {
2635 timeProvider.onPaused(msg.what == MEDIA_PAUSED);
2636 }
Lajos Molnar3d998562013-08-15 17:05:05 -07002637 }
2638 break;
2639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 case MEDIA_BUFFERING_UPDATE:
2641 if (mOnBufferingUpdateListener != null)
2642 mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
2643 return;
2644
2645 case MEDIA_SEEK_COMPLETE:
Wei Jiaaf2d2ac2015-03-30 11:16:29 -07002646 if (mOnSeekCompleteListener != null) {
2647 mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
2648 }
2649 // fall through
Lajos Molnard58b1222013-09-24 18:04:23 -07002650
2651 case MEDIA_SKIPPED:
Wei Jiaaf2d2ac2015-03-30 11:16:29 -07002652 {
2653 TimeProvider timeProvider = mTimeProvider;
2654 if (timeProvider != null) {
2655 timeProvider.onSeekComplete(mMediaPlayer);
2656 }
2657 }
2658 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659
2660 case MEDIA_SET_VIDEO_SIZE:
Wei Jiaaf2d2ac2015-03-30 11:16:29 -07002661 if (mOnVideoSizeChangedListener != null) {
2662 mOnVideoSizeChangedListener.onVideoSizeChanged(
2663 mMediaPlayer, msg.arg1, msg.arg2);
2664 }
2665 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666
2667 case MEDIA_ERROR:
2668 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
2669 boolean error_was_handled = false;
2670 if (mOnErrorListener != null) {
2671 error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
2672 }
2673 if (mOnCompletionListener != null && ! error_was_handled) {
2674 mOnCompletionListener.onCompletion(mMediaPlayer);
2675 }
2676 stayAwake(false);
2677 return;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002678
2679 case MEDIA_INFO:
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002680 switch (msg.arg1) {
2681 case MEDIA_INFO_VIDEO_TRACK_LAGGING:
Andreas Huber52c78322011-01-11 15:05:28 -08002682 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002683 break;
2684 case MEDIA_INFO_METADATA_UPDATE:
2685 scanInternalSubtitleTracks();
Lajos Molnar9d480892013-09-11 22:10:01 -07002686 // fall through
2687
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002688 case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
2689 msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
Lajos Molnar9d480892013-09-11 22:10:01 -07002690 // update default track selection
Chong Zhang70260202014-06-24 10:53:26 -07002691 if (mSubtitleController != null) {
2692 mSubtitleController.selectDefaultTrack();
2693 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002694 break;
Andreas Huber52c78322011-01-11 15:05:28 -08002695 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002696
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002697 if (mOnInfoListener != null) {
2698 mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
2699 }
2700 // No real default action so far.
2701 return;
Gloria Wang162ee492011-04-11 17:23:27 -07002702 case MEDIA_TIMED_TEXT:
Insun Kang41f3f712012-02-16 20:28:27 +09002703 if (mOnTimedTextListener == null)
2704 return;
2705 if (msg.obj == null) {
2706 mOnTimedTextListener.onTimedText(mMediaPlayer, null);
2707 } else {
Insun Kang89020972012-05-01 14:13:19 +09002708 if (msg.obj instanceof Parcel) {
2709 Parcel parcel = (Parcel)msg.obj;
2710 TimedText text = new TimedText(parcel);
Insun Kang333c0992012-07-10 12:47:03 +09002711 parcel.recycle();
Insun Kang41f3f712012-02-16 20:28:27 +09002712 mOnTimedTextListener.onTimedText(mMediaPlayer, text);
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002713 }
Gloria Wang162ee492011-04-11 17:23:27 -07002714 }
2715 return;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002716
Chong Zhang83ddaf62013-08-06 09:43:22 -07002717 case MEDIA_SUBTITLE_DATA:
2718 if (mOnSubtitleDataListener == null) {
2719 return;
2720 }
2721 if (msg.obj instanceof Parcel) {
2722 Parcel parcel = (Parcel) msg.obj;
2723 SubtitleData data = new SubtitleData(parcel);
2724 parcel.recycle();
2725 mOnSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
2726 }
2727 return;
2728
Robert Shihac033f02015-04-10 11:15:02 -07002729 case MEDIA_META_DATA:
2730 if (mOnTimedMetaDataListener == null) {
2731 return;
2732 }
2733 if (msg.obj instanceof Parcel) {
2734 Parcel parcel = (Parcel) msg.obj;
2735 TimedMetaData data = TimedMetaData.createTimedMetaDataFromParcel(parcel);
2736 parcel.recycle();
2737 mOnTimedMetaDataListener.onTimedMetaData(mMediaPlayer, data);
2738 }
2739 return;
2740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 case MEDIA_NOP: // interface test message - ignore
2742 break;
2743
2744 default:
2745 Log.e(TAG, "Unknown message type " + msg.what);
2746 return;
2747 }
2748 }
2749 }
2750
Insun Kang41f3f712012-02-16 20:28:27 +09002751 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 * Called from native code when an interesting event happens. This method
2753 * just uses the EventHandler system to post the event back to the main app thread.
2754 * We use a weak reference to the original MediaPlayer object so that the native
2755 * code is safe from the object disappearing from underneath it. (This is
2756 * the cookie passed to native_setup().)
2757 */
2758 private static void postEventFromNative(Object mediaplayer_ref,
2759 int what, int arg1, int arg2, Object obj)
2760 {
2761 MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
2762 if (mp == null) {
2763 return;
2764 }
2765
Marco Nelissen84b83202012-02-28 16:07:44 -08002766 if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
2767 // this acquires the wakelock if needed, and sets the client side state
2768 mp.start();
2769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 if (mp.mEventHandler != null) {
2771 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
2772 mp.mEventHandler.sendMessage(m);
2773 }
2774 }
2775
2776 /**
2777 * Interface definition for a callback to be invoked when the media
2778 * source is ready for playback.
2779 */
2780 public interface OnPreparedListener
2781 {
2782 /**
2783 * Called when the media file is ready for playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07002784 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 * @param mp the MediaPlayer that is ready for playback
2786 */
2787 void onPrepared(MediaPlayer mp);
2788 }
2789
2790 /**
2791 * Register a callback to be invoked when the media source is ready
2792 * for playback.
2793 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002794 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002796 public void setOnPreparedListener(OnPreparedListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002798 mOnPreparedListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 }
2800
2801 private OnPreparedListener mOnPreparedListener;
2802
2803 /**
2804 * Interface definition for a callback to be invoked when playback of
2805 * a media source has completed.
2806 */
2807 public interface OnCompletionListener
2808 {
2809 /**
2810 * Called when the end of a media source is reached during playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07002811 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 * @param mp the MediaPlayer that reached the end of the file
2813 */
2814 void onCompletion(MediaPlayer mp);
2815 }
2816
2817 /**
2818 * Register a callback to be invoked when the end of a media source
2819 * has been reached during playback.
2820 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002821 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002823 public void setOnCompletionListener(OnCompletionListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002825 mOnCompletionListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827
2828 private OnCompletionListener mOnCompletionListener;
2829
2830 /**
2831 * Interface definition of a callback to be invoked indicating buffering
2832 * status of a media resource being streamed over the network.
2833 */
2834 public interface OnBufferingUpdateListener
2835 {
2836 /**
Jean-Michel Triviea763062011-04-06 10:34:09 -07002837 * Called to update status in buffering a media stream received through
2838 * progressive HTTP download. The received buffering percentage
2839 * indicates how much of the content has been buffered or played.
2840 * For example a buffering update of 80 percent when half the content
2841 * has already been played indicates that the next 30 percent of the
2842 * content to play has been buffered.
Nicolas Catania32f82772009-06-11 16:33:49 -07002843 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 * @param mp the MediaPlayer the update pertains to
Jean-Michel Triviea763062011-04-06 10:34:09 -07002845 * @param percent the percentage (0-100) of the content
2846 * that has been buffered or played thus far
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 */
2848 void onBufferingUpdate(MediaPlayer mp, int percent);
2849 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 /**
2852 * Register a callback to be invoked when the status of a network
2853 * stream's buffer has changed.
2854 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002855 * @param listener the callback that will be run.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002857 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002859 mOnBufferingUpdateListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861
2862 private OnBufferingUpdateListener mOnBufferingUpdateListener;
Nicolas Catania32f82772009-06-11 16:33:49 -07002863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 /**
2865 * Interface definition of a callback to be invoked indicating
2866 * the completion of a seek operation.
2867 */
2868 public interface OnSeekCompleteListener
2869 {
2870 /**
2871 * Called to indicate the completion of a seek operation.
Nicolas Catania32f82772009-06-11 16:33:49 -07002872 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 * @param mp the MediaPlayer that issued the seek operation
2874 */
2875 public void onSeekComplete(MediaPlayer mp);
2876 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 /**
2879 * Register a callback to be invoked when a seek operation has been
2880 * completed.
Nicolas Catania32f82772009-06-11 16:33:49 -07002881 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002882 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002884 public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002886 mOnSeekCompleteListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 private OnSeekCompleteListener mOnSeekCompleteListener;
2890
2891 /**
2892 * Interface definition of a callback to be invoked when the
2893 * video size is first known or updated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 */
2895 public interface OnVideoSizeChangedListener
2896 {
2897 /**
2898 * Called to indicate the video size
Nicolas Catania32f82772009-06-11 16:33:49 -07002899 *
James Dongca402cd2011-12-06 17:55:38 -08002900 * The video size (width and height) could be 0 if there was no video,
2901 * no display surface was set, or the value was not determined yet.
2902 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 * @param mp the MediaPlayer associated with this callback
2904 * @param width the width of the video
2905 * @param height the height of the video
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 */
2907 public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
2908 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 /**
2911 * Register a callback to be invoked when the video size is
2912 * known or updated.
Nicolas Catania32f82772009-06-11 16:33:49 -07002913 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002914 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002916 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002918 mOnVideoSizeChangedListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
2922
Gloria Wang162ee492011-04-11 17:23:27 -07002923 /**
2924 * Interface definition of a callback to be invoked when a
2925 * timed text is available for display.
Gloria Wang162ee492011-04-11 17:23:27 -07002926 */
2927 public interface OnTimedTextListener
2928 {
2929 /**
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002930 * Called to indicate an avaliable timed text
Gloria Wang162ee492011-04-11 17:23:27 -07002931 *
2932 * @param mp the MediaPlayer associated with this callback
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002933 * @param text the timed text sample which contains the text
2934 * needed to be displayed and the display format.
Gloria Wang162ee492011-04-11 17:23:27 -07002935 */
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002936 public void onTimedText(MediaPlayer mp, TimedText text);
Gloria Wang162ee492011-04-11 17:23:27 -07002937 }
2938
2939 /**
2940 * Register a callback to be invoked when a timed text is available
2941 * for display.
2942 *
2943 * @param listener the callback that will be run
Gloria Wang162ee492011-04-11 17:23:27 -07002944 */
2945 public void setOnTimedTextListener(OnTimedTextListener listener)
2946 {
2947 mOnTimedTextListener = listener;
2948 }
2949
2950 private OnTimedTextListener mOnTimedTextListener;
2951
Chong Zhang83ddaf62013-08-06 09:43:22 -07002952 /**
2953 * Interface definition of a callback to be invoked when a
2954 * track has data available.
2955 *
2956 * @hide
2957 */
2958 public interface OnSubtitleDataListener
2959 {
2960 public void onSubtitleData(MediaPlayer mp, SubtitleData data);
2961 }
2962
2963 /**
2964 * Register a callback to be invoked when a track has data available.
2965 *
2966 * @param listener the callback that will be run
2967 *
2968 * @hide
2969 */
2970 public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
2971 {
2972 mOnSubtitleDataListener = listener;
2973 }
2974
2975 private OnSubtitleDataListener mOnSubtitleDataListener;
Gloria Wang162ee492011-04-11 17:23:27 -07002976
Robert Shihac033f02015-04-10 11:15:02 -07002977 /**
2978 * Interface definition of a callback to be invoked when a
2979 * track has timed metadata available.
2980 *
2981 * @see MediaPlayer#setOnTimedMetaDataListener(OnTimedMetaDataListener)
2982 */
2983 public interface OnTimedMetaDataListener
2984 {
2985 /**
2986 * Called to indicate avaliable timed metadata
2987 * <p>
2988 * This method will be called as timed metadata is extracted from the media,
2989 * in the same order as it occurs in the media. The timing of this event is
2990 * not controlled by the associated timestamp.
2991 *
2992 * @param mp the MediaPlayer associated with this callback
2993 * @param data the timed metadata sample associated with this event
2994 */
2995 public void onTimedMetaData(MediaPlayer mp, TimedMetaData data);
2996 }
2997
2998 /**
2999 * Register a callback to be invoked when a selected track has timed metadata available.
3000 * <p>
3001 * Currently only HTTP live streaming data URI's embedded with timed ID3 tags generates
3002 * {@link TimedMetaData}.
3003 *
3004 * @see MediaPlayer#selectTrack(int)
3005 * @see MediaPlayer.OnTimedMetaDataListener
3006 * @see TimedMetaData
3007 *
3008 * @param listener the callback that will be run
3009 */
3010 public void setOnTimedMetaDataListener(OnTimedMetaDataListener listener)
3011 {
3012 mOnTimedMetaDataListener = listener;
3013 }
3014
3015 private OnTimedMetaDataListener mOnTimedMetaDataListener;
3016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 /* Do not change these values without updating their counterparts
3018 * in include/media/mediaplayer.h!
3019 */
3020 /** Unspecified media player error.
3021 * @see android.media.MediaPlayer.OnErrorListener
3022 */
3023 public static final int MEDIA_ERROR_UNKNOWN = 1;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 /** Media server died. In this case, the application must release the
Nicolas Catania32f82772009-06-11 16:33:49 -07003026 * MediaPlayer object and instantiate a new one.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 * @see android.media.MediaPlayer.OnErrorListener
3028 */
3029 public static final int MEDIA_ERROR_SERVER_DIED = 100;
Nicolas Catania32f82772009-06-11 16:33:49 -07003030
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003031 /** The video is streamed and its container is not valid for progressive
3032 * playback i.e the video's index (e.g moov atom) is not at the start of the
3033 * file.
Niko Catania4a0029f2009-03-24 19:51:09 -07003034 * @see android.media.MediaPlayer.OnErrorListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003035 */
3036 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037
James Dong2adac492012-08-26 13:00:30 -07003038 /** File or network related operation errors. */
3039 public static final int MEDIA_ERROR_IO = -1004;
3040 /** Bitstream is not conforming to the related coding standard or file spec. */
3041 public static final int MEDIA_ERROR_MALFORMED = -1007;
3042 /** Bitstream is conforming to the related coding standard or file spec, but
3043 * the media framework does not support the feature. */
3044 public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
3045 /** Some operation takes too long to complete, usually more than 3-5 seconds. */
3046 public static final int MEDIA_ERROR_TIMED_OUT = -110;
3047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 /**
3049 * Interface definition of a callback to be invoked when there
3050 * has been an error during an asynchronous operation (other errors
3051 * will throw exceptions at method call time).
3052 */
3053 public interface OnErrorListener
3054 {
3055 /**
3056 * Called to indicate an error.
Nicolas Catania32f82772009-06-11 16:33:49 -07003057 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 * @param mp the MediaPlayer the error pertains to
3059 * @param what the type of error that has occurred:
3060 * <ul>
3061 * <li>{@link #MEDIA_ERROR_UNKNOWN}
3062 * <li>{@link #MEDIA_ERROR_SERVER_DIED}
3063 * </ul>
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003064 * @param extra an extra code, specific to the error. Typically
James Dongb10ec1f2012-07-30 15:43:14 -07003065 * implementation dependent.
James Dong2adac492012-08-26 13:00:30 -07003066 * <ul>
3067 * <li>{@link #MEDIA_ERROR_IO}
3068 * <li>{@link #MEDIA_ERROR_MALFORMED}
3069 * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
3070 * <li>{@link #MEDIA_ERROR_TIMED_OUT}
3071 * </ul>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 * @return True if the method handled the error, false if it didn't.
3073 * Returning false, or not having an OnErrorListener at all, will
3074 * cause the OnCompletionListener to be called.
3075 */
3076 boolean onError(MediaPlayer mp, int what, int extra);
3077 }
Nicolas Catania32f82772009-06-11 16:33:49 -07003078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 /**
3080 * Register a callback to be invoked when an error has happened
3081 * during an asynchronous operation.
Nicolas Catania32f82772009-06-11 16:33:49 -07003082 *
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003083 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 */
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003085 public void setOnErrorListener(OnErrorListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003087 mOnErrorListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
3089
3090 private OnErrorListener mOnErrorListener;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003091
3092
3093 /* Do not change these values without updating their counterparts
3094 * in include/media/mediaplayer.h!
3095 */
3096 /** Unspecified media player info.
3097 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003098 */
3099 public static final int MEDIA_INFO_UNKNOWN = 1;
3100
Marco Nelissen84b83202012-02-28 16:07:44 -08003101 /** The player was started because it was used as the next player for another
3102 * player, which just completed playback.
3103 * @see android.media.MediaPlayer.OnInfoListener
3104 * @hide
3105 */
3106 public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
3107
James Dong15a89e62012-07-23 15:00:37 -07003108 /** The player just pushed the very first video frame for rendering.
3109 * @see android.media.MediaPlayer.OnInfoListener
3110 */
3111 public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
3112
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003113 /** The video is too complex for the decoder: it can't decode frames fast
3114 * enough. Possibly only the audio plays fine at this stage.
3115 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003116 */
3117 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
3118
Andreas Huber4d61f602010-06-10 11:17:50 -07003119 /** MediaPlayer is temporarily pausing playback internally in order to
3120 * buffer more data.
James Dongc36b3c62011-03-29 12:16:59 -07003121 * @see android.media.MediaPlayer.OnInfoListener
Andreas Huber4d61f602010-06-10 11:17:50 -07003122 */
3123 public static final int MEDIA_INFO_BUFFERING_START = 701;
3124
3125 /** MediaPlayer is resuming playback after filling buffers.
James Dongc36b3c62011-03-29 12:16:59 -07003126 * @see android.media.MediaPlayer.OnInfoListener
Andreas Huber4d61f602010-06-10 11:17:50 -07003127 */
3128 public static final int MEDIA_INFO_BUFFERING_END = 702;
3129
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003130 /** Bad interleaving means that a media has been improperly interleaved or
3131 * not interleaved at all, e.g has all the video samples first then all the
3132 * audio ones. Video is playing but a lot of disk seeks may be happening.
3133 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003134 */
3135 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
3136
3137 /** The media cannot be seeked (e.g live stream)
3138 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003139 */
3140 public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
3141
Nicolas Catania9193e082009-07-06 12:43:36 -07003142 /** A new set of metadata is available.
3143 * @see android.media.MediaPlayer.OnInfoListener
3144 */
3145 public static final int MEDIA_INFO_METADATA_UPDATE = 802;
3146
Lajos Molnar484ff7a92013-08-15 11:37:47 -07003147 /** A new set of external-only metadata is available. Used by
3148 * JAVA framework to avoid triggering track scanning.
3149 * @hide
3150 */
3151 public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
3152
Insun Kang41f3f712012-02-16 20:28:27 +09003153 /** Failed to handle timed text track properly.
3154 * @see android.media.MediaPlayer.OnInfoListener
3155 *
3156 * {@hide}
3157 */
3158 public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
3159
Lajos Molnaraf3098242013-08-15 20:56:53 -07003160 /** Subtitle track was not supported by the media framework.
3161 * @see android.media.MediaPlayer.OnInfoListener
3162 */
3163 public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
3164
3165 /** Reading the subtitle track takes too long.
3166 * @see android.media.MediaPlayer.OnInfoListener
3167 */
3168 public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
3169
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003170 /**
3171 * Interface definition of a callback to be invoked to communicate some
3172 * info and/or warning about the media or its playback.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003173 */
3174 public interface OnInfoListener
3175 {
3176 /**
3177 * Called to indicate an info or a warning.
Nicolas Catania32f82772009-06-11 16:33:49 -07003178 *
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003179 * @param mp the MediaPlayer the info pertains to.
3180 * @param what the type of info or warning.
3181 * <ul>
3182 * <li>{@link #MEDIA_INFO_UNKNOWN}
3183 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
James Dong15a89e62012-07-23 15:00:37 -07003184 * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
James Dongc36b3c62011-03-29 12:16:59 -07003185 * <li>{@link #MEDIA_INFO_BUFFERING_START}
3186 * <li>{@link #MEDIA_INFO_BUFFERING_END}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003187 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
3188 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
Nicolas Catania9193e082009-07-06 12:43:36 -07003189 * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
Lajos Molnaraf3098242013-08-15 20:56:53 -07003190 * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
3191 * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003192 * </ul>
3193 * @param extra an extra code, specific to the info. Typically
James Dongb10ec1f2012-07-30 15:43:14 -07003194 * implementation dependent.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003195 * @return True if the method handled the info, false if it didn't.
3196 * Returning false, or not having an OnErrorListener at all, will
3197 * cause the info to be discarded.
3198 */
3199 boolean onInfo(MediaPlayer mp, int what, int extra);
3200 }
3201
3202 /**
3203 * Register a callback to be invoked when an info/warning is available.
Nicolas Catania32f82772009-06-11 16:33:49 -07003204 *
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003205 * @param listener the callback that will be run
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003206 */
3207 public void setOnInfoListener(OnInfoListener listener)
3208 {
3209 mOnInfoListener = listener;
3210 }
3211
3212 private OnInfoListener mOnInfoListener;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07003213
James Dong454014e2012-04-28 16:03:55 -07003214 /*
3215 * Test whether a given video scaling mode is supported.
3216 */
3217 private boolean isVideoScalingModeSupported(int mode) {
3218 return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
3219 mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
3220 }
Andreas Huberd5f9fa52013-05-28 14:39:39 -07003221
Wei Jiad93fcf42015-02-09 16:05:53 -08003222 /*
3223 * Test whether a given audio playback mode is supported.
3224 * TODO query supported AudioPlaybackMode from player.
3225 */
3226 private boolean isAudioPlaybackModeSupported(int mode) {
3227 return (mode == PLAYBACK_RATE_AUDIO_MODE_RESAMPLE);
3228 }
3229
Lajos Molnar3d998562013-08-15 17:05:05 -07003230 /** @hide */
3231 static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
3232 MediaTimeProvider {
3233 private static final String TAG = "MTP";
3234 private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
3235 private static final long MAX_EARLY_CALLBACK_US = 1000;
3236 private static final long TIME_ADJUSTMENT_RATE = 2; /* meaning 1/2 */
3237 private long mLastTimeUs = 0;
3238 private MediaPlayer mPlayer;
3239 private boolean mPaused = true;
3240 private boolean mStopped = true;
3241 private long mLastReportedTime;
3242 private long mTimeAdjustment;
3243 // since we are expecting only a handful listeners per stream, there is
3244 // no need for log(N) search performance
3245 private MediaTimeProvider.OnMediaTimeListener mListeners[];
3246 private long mTimes[];
3247 private long mLastNanoTime;
3248 private Handler mEventHandler;
3249 private boolean mRefresh = false;
3250 private boolean mPausing = false;
Lajos Molnard58b1222013-09-24 18:04:23 -07003251 private boolean mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07003252 private static final int NOTIFY = 1;
3253 private static final int NOTIFY_TIME = 0;
3254 private static final int REFRESH_AND_NOTIFY_TIME = 1;
3255 private static final int NOTIFY_STOP = 2;
3256 private static final int NOTIFY_SEEK = 3;
Lajos Molnara67a4432013-09-06 06:30:35 -07003257 private HandlerThread mHandlerThread;
Lajos Molnar3d998562013-08-15 17:05:05 -07003258
3259 /** @hide */
3260 public boolean DEBUG = false;
3261
3262 public TimeProvider(MediaPlayer mp) {
3263 mPlayer = mp;
3264 try {
3265 getCurrentTimeUs(true, false);
3266 } catch (IllegalStateException e) {
3267 // we assume starting position
3268 mRefresh = true;
3269 }
Lajos Molnara67a4432013-09-06 06:30:35 -07003270
3271 Looper looper;
3272 if ((looper = Looper.myLooper()) == null &&
3273 (looper = Looper.getMainLooper()) == null) {
3274 // Create our own looper here in case MP was created without one
3275 mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
3276 Process.THREAD_PRIORITY_FOREGROUND);
3277 mHandlerThread.start();
3278 looper = mHandlerThread.getLooper();
3279 }
3280 mEventHandler = new EventHandler(looper);
3281
Lajos Molnar3d998562013-08-15 17:05:05 -07003282 mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
3283 mTimes = new long[0];
3284 mLastTimeUs = 0;
3285 mTimeAdjustment = 0;
3286 }
3287
3288 private void scheduleNotification(int type, long delayUs) {
Lajos Molnard58b1222013-09-24 18:04:23 -07003289 // ignore time notifications until seek is handled
3290 if (mSeeking &&
3291 (type == NOTIFY_TIME || type == REFRESH_AND_NOTIFY_TIME)) {
3292 return;
3293 }
3294
Lajos Molnar3d998562013-08-15 17:05:05 -07003295 if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
3296 mEventHandler.removeMessages(NOTIFY);
3297 Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
3298 mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
3299 }
3300
3301 /** @hide */
3302 public void close() {
3303 mEventHandler.removeMessages(NOTIFY);
Lajos Molnara67a4432013-09-06 06:30:35 -07003304 if (mHandlerThread != null) {
3305 mHandlerThread.quitSafely();
3306 mHandlerThread = null;
3307 }
3308 }
3309
3310 /** @hide */
3311 protected void finalize() {
3312 if (mHandlerThread != null) {
3313 mHandlerThread.quitSafely();
3314 }
Lajos Molnar3d998562013-08-15 17:05:05 -07003315 }
3316
3317 /** @hide */
3318 public void onPaused(boolean paused) {
3319 synchronized(this) {
3320 if (DEBUG) Log.d(TAG, "onPaused: " + paused);
3321 if (mStopped) { // handle as seek if we were stopped
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07003322 mStopped = false;
3323 mSeeking = true;
Lajos Molnar3d998562013-08-15 17:05:05 -07003324 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
3325 } else {
3326 mPausing = paused; // special handling if player disappeared
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07003327 mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07003328 scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
3329 }
3330 }
3331 }
3332
3333 /** @hide */
3334 public void onStopped() {
3335 synchronized(this) {
3336 if (DEBUG) Log.d(TAG, "onStopped");
3337 mPaused = true;
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07003338 mStopped = true;
3339 mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07003340 scheduleNotification(NOTIFY_STOP, 0 /* delay */);
3341 }
3342 }
3343
3344 /** @hide */
3345 @Override
3346 public void onSeekComplete(MediaPlayer mp) {
3347 synchronized(this) {
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07003348 mStopped = false;
3349 mSeeking = true;
Lajos Molnar3d998562013-08-15 17:05:05 -07003350 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
3351 }
3352 }
3353
3354 /** @hide */
3355 public void onNewPlayer() {
3356 if (mRefresh) {
3357 synchronized(this) {
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07003358 mStopped = false;
3359 mSeeking = true;
Lajos Molnar3d998562013-08-15 17:05:05 -07003360 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
3361 }
3362 }
3363 }
3364
3365 private synchronized void notifySeek() {
Lajos Molnard58b1222013-09-24 18:04:23 -07003366 mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07003367 try {
3368 long timeUs = getCurrentTimeUs(true, false);
3369 if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
3370
3371 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
3372 if (listener == null) {
3373 break;
3374 }
3375 listener.onSeek(timeUs);
3376 }
3377 } catch (IllegalStateException e) {
3378 // we should not be there, but at least signal pause
3379 if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
3380 mPausing = true; // special handling if player disappeared
3381 notifyTimedEvent(false /* refreshTime */);
3382 }
3383 }
3384
3385 private synchronized void notifyStop() {
3386 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
3387 if (listener == null) {
3388 break;
3389 }
3390 listener.onStop();
3391 }
3392 }
3393
3394 private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
3395 int i = 0;
3396 for (; i < mListeners.length; i++) {
3397 if (mListeners[i] == listener || mListeners[i] == null) {
3398 break;
3399 }
3400 }
3401
3402 // new listener
3403 if (i >= mListeners.length) {
3404 MediaTimeProvider.OnMediaTimeListener[] newListeners =
3405 new MediaTimeProvider.OnMediaTimeListener[i + 1];
3406 long[] newTimes = new long[i + 1];
3407 System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
3408 System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
3409 mListeners = newListeners;
3410 mTimes = newTimes;
3411 }
3412
3413 if (mListeners[i] == null) {
3414 mListeners[i] = listener;
3415 mTimes[i] = MediaTimeProvider.NO_TIME;
3416 }
3417 return i;
3418 }
3419
3420 public void notifyAt(
3421 long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
3422 synchronized(this) {
3423 if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
3424 mTimes[registerListener(listener)] = timeUs;
3425 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
3426 }
3427 }
3428
3429 public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
3430 synchronized(this) {
3431 if (DEBUG) Log.d(TAG, "scheduleUpdate");
3432 int i = registerListener(listener);
3433
Robert Shih8c4d53c2014-09-05 13:33:31 -07003434 if (!mStopped) {
Lajos Molnar3d998562013-08-15 17:05:05 -07003435 mTimes[i] = 0;
3436 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
3437 }
3438 }
3439 }
3440
3441 public void cancelNotifications(
3442 MediaTimeProvider.OnMediaTimeListener listener) {
3443 synchronized(this) {
3444 int i = 0;
3445 for (; i < mListeners.length; i++) {
3446 if (mListeners[i] == listener) {
3447 System.arraycopy(mListeners, i + 1,
3448 mListeners, i, mListeners.length - i - 1);
3449 System.arraycopy(mTimes, i + 1,
3450 mTimes, i, mTimes.length - i - 1);
3451 mListeners[mListeners.length - 1] = null;
3452 mTimes[mTimes.length - 1] = NO_TIME;
3453 break;
3454 } else if (mListeners[i] == null) {
3455 break;
3456 }
3457 }
3458
3459 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
3460 }
3461 }
3462
3463 private synchronized void notifyTimedEvent(boolean refreshTime) {
3464 // figure out next callback
3465 long nowUs;
3466 try {
3467 nowUs = getCurrentTimeUs(refreshTime, true);
3468 } catch (IllegalStateException e) {
3469 // assume we paused until new player arrives
3470 mRefresh = true;
3471 mPausing = true; // this ensures that call succeeds
3472 nowUs = getCurrentTimeUs(refreshTime, true);
3473 }
3474 long nextTimeUs = nowUs;
3475
Lajos Molnard58b1222013-09-24 18:04:23 -07003476 if (mSeeking) {
3477 // skip timed-event notifications until seek is complete
3478 return;
3479 }
3480
Lajos Molnar3d998562013-08-15 17:05:05 -07003481 if (DEBUG) {
3482 StringBuilder sb = new StringBuilder();
3483 sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
3484 .append(nowUs).append(") from {");
3485 boolean first = true;
3486 for (long time: mTimes) {
3487 if (time == NO_TIME) {
3488 continue;
3489 }
3490 if (!first) sb.append(", ");
3491 sb.append(time);
3492 first = false;
3493 }
3494 sb.append("}");
3495 Log.d(TAG, sb.toString());
3496 }
3497
3498 Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
3499 new Vector<MediaTimeProvider.OnMediaTimeListener>();
3500 for (int ix = 0; ix < mTimes.length; ix++) {
3501 if (mListeners[ix] == null) {
3502 break;
3503 }
3504 if (mTimes[ix] <= NO_TIME) {
3505 // ignore, unless we were stopped
3506 } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
3507 activatedListeners.add(mListeners[ix]);
3508 if (DEBUG) Log.d(TAG, "removed");
3509 mTimes[ix] = NO_TIME;
3510 } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
3511 nextTimeUs = mTimes[ix];
3512 }
3513 }
3514
3515 if (nextTimeUs > nowUs && !mPaused) {
3516 // schedule callback at nextTimeUs
3517 if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
3518 scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
3519 } else {
3520 mEventHandler.removeMessages(NOTIFY);
3521 // no more callbacks
3522 }
3523
3524 for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
3525 listener.onTimedEvent(nowUs);
3526 }
3527 }
3528
3529 private long getEstimatedTime(long nanoTime, boolean monotonic) {
3530 if (mPaused) {
3531 mLastReportedTime = mLastTimeUs + mTimeAdjustment;
3532 } else {
3533 long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
3534 mLastReportedTime = mLastTimeUs + timeSinceRead;
3535 if (mTimeAdjustment > 0) {
3536 long adjustment =
3537 mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
3538 if (adjustment <= 0) {
3539 mTimeAdjustment = 0;
3540 } else {
3541 mLastReportedTime += adjustment;
3542 }
3543 }
3544 }
3545 return mLastReportedTime;
3546 }
3547
3548 public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
3549 throws IllegalStateException {
3550 synchronized (this) {
3551 // we always refresh the time when the paused-state changes, because
3552 // we expect to have received the pause-change event delayed.
3553 if (mPaused && !refreshTime) {
3554 return mLastReportedTime;
3555 }
3556
3557 long nanoTime = System.nanoTime();
3558 if (refreshTime ||
3559 nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
3560 try {
Lajos Molnar7246fa52014-03-10 17:21:49 -07003561 mLastTimeUs = mPlayer.getCurrentPosition() * 1000L;
Lajos Molnar3d998562013-08-15 17:05:05 -07003562 mPaused = !mPlayer.isPlaying();
3563 if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
3564 } catch (IllegalStateException e) {
3565 if (mPausing) {
3566 // if we were pausing, get last estimated timestamp
3567 mPausing = false;
3568 getEstimatedTime(nanoTime, monotonic);
3569 mPaused = true;
3570 if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
3571 return mLastReportedTime;
3572 }
3573 // TODO get time when prepared
3574 throw e;
3575 }
3576 mLastNanoTime = nanoTime;
3577 if (monotonic && mLastTimeUs < mLastReportedTime) {
3578 /* have to adjust time */
3579 mTimeAdjustment = mLastReportedTime - mLastTimeUs;
Lajos Molnard58b1222013-09-24 18:04:23 -07003580 if (mTimeAdjustment > 1000000) {
3581 // schedule seeked event if time jumped significantly
3582 // TODO: do this properly by introducing an exception
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07003583 mStopped = false;
3584 mSeeking = true;
Lajos Molnard58b1222013-09-24 18:04:23 -07003585 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
3586 }
Lajos Molnar3d998562013-08-15 17:05:05 -07003587 } else {
3588 mTimeAdjustment = 0;
3589 }
3590 }
3591
3592 return getEstimatedTime(nanoTime, monotonic);
3593 }
3594 }
3595
3596 private class EventHandler extends Handler {
Lajos Molnara67a4432013-09-06 06:30:35 -07003597 public EventHandler(Looper looper) {
3598 super(looper);
3599 }
3600
Lajos Molnar3d998562013-08-15 17:05:05 -07003601 @Override
3602 public void handleMessage(Message msg) {
3603 if (msg.what == NOTIFY) {
3604 switch (msg.arg1) {
3605 case NOTIFY_TIME:
3606 notifyTimedEvent(false /* refreshTime */);
3607 break;
3608 case REFRESH_AND_NOTIFY_TIME:
3609 notifyTimedEvent(true /* refreshTime */);
3610 break;
3611 case NOTIFY_STOP:
3612 notifyStop();
3613 break;
3614 case NOTIFY_SEEK:
3615 notifySeek();
3616 break;
3617 }
3618 }
3619 }
3620 }
Lajos Molnar3d998562013-08-15 17:05:05 -07003621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622}