MediaRecorder.java revision 029d7e15f38cdd3c1941a16186c5941edc85bc3d
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
19import android.hardware.Camera;
20import android.os.Handler;
21import android.os.Looper;
22import android.os.Message;
23import android.util.Log;
24import android.view.Surface;
25
26import java.io.FileDescriptor;
27import java.io.FileOutputStream;
28import java.io.IOException;
29import java.lang.ref.WeakReference;
30
31/**
32 * Used to record audio and video. The recording control is based on a
33 * simple state machine (see below).
34 *
35 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" />
36 * </p>
37 *
38 * <p>A common case of using MediaRecorder to record audio works as follows:
39 *
40 * <pre>MediaRecorder recorder = new MediaRecorder();
41 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
42 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
43 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
44 * recorder.setOutputFile(PATH_NAME);
45 * recorder.prepare();
46 * recorder.start();   // Recording is now started
47 * ...
48 * recorder.stop();
49 * recorder.reset();   // You can reuse the object by going back to setAudioSource() step
50 * recorder.release(); // Now the object cannot be reused
51 * </pre>
52 *
53 * <p>Applications may want to register for informational and error
54 * events in order to be informed of some internal update and possible
55 * runtime errors during recording. Registration for such events is
56 * done by setting the appropriate listeners (via calls
57 * (to {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener and/or
58 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener).
59 * In order to receive the respective callback associated with these listeners,
60 * applications are required to create MediaRecorder objects on threads with a
61 * Looper running (the main UI thread by default already has a Looper running).
62 *
63 * <p><strong>Note:</strong> Currently, MediaRecorder does not work on the emulator.
64 *
65 * <div class="special reference">
66 * <h3>Developer Guides</h3>
67 * <p>For more information about how to use MediaRecorder for recording video, read the
68 * <a href="{@docRoot}guide/topics/media/camera.html#capture-video">Camera</a> developer guide.
69 * For more information about how to use MediaRecorder for recording sound, read the
70 * <a href="{@docRoot}guide/topics/media/audio-capture.html">Audio Capture</a> developer guide.</p>
71 * </div>
72 */
73public class MediaRecorder
74{
75    static {
76        System.loadLibrary("media_jni");
77        native_init();
78    }
79    private final static String TAG = "MediaRecorder";
80
81    // The two fields below are accessed by native methods
82    @SuppressWarnings("unused")
83    private int mNativeContext;
84
85    @SuppressWarnings("unused")
86    private Surface mSurface;
87
88    private String mPath;
89    private FileDescriptor mFd;
90    private EventHandler mEventHandler;
91    private OnErrorListener mOnErrorListener;
92    private OnInfoListener mOnInfoListener;
93
94    /**
95     * Default constructor.
96     */
97    public MediaRecorder() {
98
99        Looper looper;
100        if ((looper = Looper.myLooper()) != null) {
101            mEventHandler = new EventHandler(this, looper);
102        } else if ((looper = Looper.getMainLooper()) != null) {
103            mEventHandler = new EventHandler(this, looper);
104        } else {
105            mEventHandler = null;
106        }
107
108        /* Native setup requires a weak reference to our object.
109         * It's easier to create it here than in C++.
110         */
111        native_setup(new WeakReference<MediaRecorder>(this));
112    }
113
114    /**
115     * Sets a Camera to use for recording. Use this function to switch
116     * quickly between preview and capture mode without a teardown of
117     * the camera object. {@link android.hardware.Camera#unlock()} should be
118     * called before this. Must call before prepare().
119     *
120     * @param c the Camera to use for recording
121     */
122    public native void setCamera(Camera c);
123
124    /**
125     * Sets a Surface to show a preview of recorded media (video). Calls this
126     * before prepare() to make sure that the desirable preview display is
127     * set.
128     *
129     * @param sv the Surface to use for the preview
130     */
131    public void setPreviewDisplay(Surface sv) {
132        mSurface = sv;
133    }
134
135    /**
136     * Defines the audio source. These constants are used with
137     * {@link MediaRecorder#setAudioSource(int)}.
138     */
139    public final class AudioSource {
140      /* Do not change these values without updating their counterparts
141       * in system/core/include/system/audio.h!
142       */
143        private AudioSource() {}
144
145        /** Default audio source **/
146        public static final int DEFAULT = 0;
147
148        /** Microphone audio source */
149        public static final int MIC = 1;
150
151        /** Voice call uplink (Tx) audio source */
152        public static final int VOICE_UPLINK = 2;
153
154        /** Voice call downlink (Rx) audio source */
155        public static final int VOICE_DOWNLINK = 3;
156
157        /** Voice call uplink + downlink audio source */
158        public static final int VOICE_CALL = 4;
159
160        /** Microphone audio source with same orientation as camera if available, the main
161         *  device microphone otherwise */
162        public static final int CAMCORDER = 5;
163
164        /** Microphone audio source tuned for voice recognition if available, behaves like
165         *  {@link #DEFAULT} otherwise. */
166        public static final int VOICE_RECOGNITION = 6;
167
168        /** Microphone audio source tuned for voice communications such as VoIP. It
169         *  will for instance take advantage of echo cancellation or automatic gain control
170         *  if available. It otherwise behaves like {@link #DEFAULT} if no voice processing
171         *  is applied.
172         */
173        public static final int VOICE_COMMUNICATION = 7;
174    }
175
176    /**
177     * Defines the video source. These constants are used with
178     * {@link MediaRecorder#setVideoSource(int)}.
179     */
180    public final class VideoSource {
181      /* Do not change these values without updating their counterparts
182       * in include/media/mediarecorder.h!
183       */
184        private VideoSource() {}
185        public static final int DEFAULT = 0;
186        /** Camera video source */
187        public static final int CAMERA = 1;
188        /** @hide */
189        public static final int GRALLOC_BUFFER = 2;
190    }
191
192    /**
193     * Defines the output format. These constants are used with
194     * {@link MediaRecorder#setOutputFormat(int)}.
195     */
196    public final class OutputFormat {
197      /* Do not change these values without updating their counterparts
198       * in include/media/mediarecorder.h!
199       */
200        private OutputFormat() {}
201        public static final int DEFAULT = 0;
202        /** 3GPP media file format*/
203        public static final int THREE_GPP = 1;
204        /** MPEG4 media file format*/
205        public static final int MPEG_4 = 2;
206
207        /** The following formats are audio only .aac or .amr formats */
208
209        /**
210         * AMR NB file format
211         * @deprecated  Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
212         */
213        public static final int RAW_AMR = 3;
214
215        /** AMR NB file format */
216        public static final int AMR_NB = 3;
217
218        /** AMR WB file format */
219        public static final int AMR_WB = 4;
220
221        /** @hide AAC ADIF file format */
222        public static final int AAC_ADIF = 5;
223
224        /** AAC ADTS file format */
225        public static final int AAC_ADTS = 6;
226
227        /** @hide Stream over a socket, limited to a single stream */
228        public static final int OUTPUT_FORMAT_RTP_AVP = 7;
229
230        /** @hide H.264/AAC data encapsulated in MPEG2/TS */
231        public static final int OUTPUT_FORMAT_MPEG2TS = 8;
232    };
233
234    /**
235     * Defines the audio encoding. These constants are used with
236     * {@link MediaRecorder#setAudioEncoder(int)}.
237     */
238    public final class AudioEncoder {
239      /* Do not change these values without updating their counterparts
240       * in include/media/mediarecorder.h!
241       */
242        private AudioEncoder() {}
243        public static final int DEFAULT = 0;
244        /** AMR (Narrowband) audio codec */
245        public static final int AMR_NB = 1;
246        /** AMR (Wideband) audio codec */
247        public static final int AMR_WB = 2;
248        /** AAC audio codec */
249        public static final int AAC = 3;
250        /** @hide enhanced AAC audio codec */
251        public static final int AAC_PLUS = 4;
252        /** @hide enhanced AAC plus audio codec */
253        public static final int EAAC_PLUS = 5;
254    }
255
256    /**
257     * Defines the video encoding. These constants are used with
258     * {@link MediaRecorder#setVideoEncoder(int)}.
259     */
260    public final class VideoEncoder {
261      /* Do not change these values without updating their counterparts
262       * in include/media/mediarecorder.h!
263       */
264        private VideoEncoder() {}
265        public static final int DEFAULT = 0;
266        public static final int H263 = 1;
267        public static final int H264 = 2;
268        public static final int MPEG_4_SP = 3;
269    }
270
271    /**
272     * Sets the audio source to be used for recording. If this method is not
273     * called, the output file will not contain an audio track. The source needs
274     * to be specified before setting recording-parameters or encoders. Call
275     * this only before setOutputFormat().
276     *
277     * @param audio_source the audio source to use
278     * @throws IllegalStateException if it is called after setOutputFormat()
279     * @see android.media.MediaRecorder.AudioSource
280     */
281    public native void setAudioSource(int audio_source)
282            throws IllegalStateException;
283
284    /**
285     * Gets the maximum value for audio sources.
286     * @see android.media.MediaRecorder.AudioSource
287     */
288    public static final int getAudioSourceMax() { return AudioSource.VOICE_COMMUNICATION; }
289
290    /**
291     * Sets the video source to be used for recording. If this method is not
292     * called, the output file will not contain an video track. The source needs
293     * to be specified before setting recording-parameters or encoders. Call
294     * this only before setOutputFormat().
295     *
296     * @param video_source the video source to use
297     * @throws IllegalStateException if it is called after setOutputFormat()
298     * @see android.media.MediaRecorder.VideoSource
299     */
300    public native void setVideoSource(int video_source)
301            throws IllegalStateException;
302
303    /**
304     * Uses the settings from a CamcorderProfile object for recording. This method should
305     * be called after the video AND audio sources are set, and before setOutputFile().
306     * If a time lapse CamcorderProfile is used, audio related source or recording
307     * parameters are ignored.
308     *
309     * @param profile the CamcorderProfile to use
310     * @see android.media.CamcorderProfile
311     */
312    public void setProfile(CamcorderProfile profile) {
313        setOutputFormat(profile.fileFormat);
314        setVideoFrameRate(profile.videoFrameRate);
315        setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
316        setVideoEncodingBitRate(profile.videoBitRate);
317        setVideoEncoder(profile.videoCodec);
318        if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW &&
319             profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) {
320            // Nothing needs to be done. Call to setCaptureRate() enables
321            // time lapse video recording.
322        } else {
323            setAudioEncodingBitRate(profile.audioBitRate);
324            setAudioChannels(profile.audioChannels);
325            setAudioSamplingRate(profile.audioSampleRate);
326            setAudioEncoder(profile.audioCodec);
327        }
328    }
329
330    /**
331     * Set video frame capture rate. This can be used to set a different video frame capture
332     * rate than the recorded video's playback rate. This method also sets the recording mode
333     * to time lapse. In time lapse video recording, only video is recorded. Audio related
334     * parameters are ignored when a time lapse recording session starts, if an application
335     * sets them.
336     *
337     * @param fps Rate at which frames should be captured in frames per second.
338     * The fps can go as low as desired. However the fastest fps will be limited by the hardware.
339     * For resolutions that can be captured by the video camera, the fastest fps can be computed using
340     * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher
341     * resolutions the fastest fps may be more restrictive.
342     * Note that the recorder cannot guarantee that frames will be captured at the
343     * given rate due to camera/encoder limitations. However it tries to be as close as
344     * possible.
345     */
346    public void setCaptureRate(double fps) {
347        // Make sure that time lapse is enabled when this method is called.
348        setParameter(String.format("time-lapse-enable=1"));
349
350        double timeBetweenFrameCapture = 1 / fps;
351        int timeBetweenFrameCaptureMs = (int) (1000 * timeBetweenFrameCapture);
352        setParameter(String.format("time-between-time-lapse-frame-capture=%d",
353                    timeBetweenFrameCaptureMs));
354    }
355
356    /**
357     * Sets the orientation hint for output video playback.
358     * This method should be called before prepare(). This method will not
359     * trigger the source video frame to rotate during video recording, but to
360     * add a composition matrix containing the rotation angle in the output
361     * video if the output format is OutputFormat.THREE_GPP or
362     * OutputFormat.MPEG_4 so that a video player can choose the proper
363     * orientation for playback. Note that some video players may choose
364     * to ignore the compostion matrix in a video during playback.
365     *
366     * @param degrees the angle to be rotated clockwise in degrees.
367     * The supported angles are 0, 90, 180, and 270 degrees.
368     * @throws IllegalArgumentException if the angle is not supported.
369     *
370     */
371    public void setOrientationHint(int degrees) {
372        if (degrees != 0   &&
373            degrees != 90  &&
374            degrees != 180 &&
375            degrees != 270) {
376            throw new IllegalArgumentException("Unsupported angle: " + degrees);
377        }
378        setParameter("video-param-rotation-angle-degrees=" + degrees);
379    }
380
381    /**
382     * Set and store the geodata (latitude and longitude) in the output file.
383     * This method should be called before prepare(). The geodata is
384     * stored in udta box if the output format is OutputFormat.THREE_GPP
385     * or OutputFormat.MPEG_4, and is ignored for other output formats.
386     * The geodata is stored according to ISO-6709 standard.
387     *
388     * @param latitude latitude in degrees. Its value must be in the
389     * range [-90, 90].
390     * @param longitude longitude in degrees. Its value must be in the
391     * range [-180, 180].
392     *
393     * @throws IllegalArgumentException if the given latitude or
394     * longitude is out of range.
395     *
396     */
397    public void setLocation(float latitude, float longitude) {
398        int latitudex10000  = (int) (latitude * 10000 + 0.5);
399        int longitudex10000 = (int) (longitude * 10000 + 0.5);
400
401        if (latitudex10000 > 900000 || latitudex10000 < -900000) {
402            String msg = "Latitude: " + latitude + " out of range.";
403            throw new IllegalArgumentException(msg);
404        }
405        if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
406            String msg = "Longitude: " + longitude + " out of range";
407            throw new IllegalArgumentException(msg);
408        }
409
410        setParameter("param-geotag-latitude=" + latitudex10000);
411        setParameter("param-geotag-longitude=" + longitudex10000);
412    }
413
414    /**
415     * Sets the format of the output file produced during recording. Call this
416     * after setAudioSource()/setVideoSource() but before prepare().
417     *
418     * <p>It is recommended to always use 3GP format when using the H.263
419     * video encoder and AMR audio encoder. Using an MPEG-4 container format
420     * may confuse some desktop players.</p>
421     *
422     * @param output_format the output format to use. The output format
423     * needs to be specified before setting recording-parameters or encoders.
424     * @throws IllegalStateException if it is called after prepare() or before
425     * setAudioSource()/setVideoSource().
426     * @see android.media.MediaRecorder.OutputFormat
427     */
428    public native void setOutputFormat(int output_format)
429            throws IllegalStateException;
430
431    /**
432     * Sets the width and height of the video to be captured.  Must be called
433     * after setVideoSource(). Call this after setOutFormat() but before
434     * prepare().
435     *
436     * @param width the width of the video to be captured
437     * @param height the height of the video to be captured
438     * @throws IllegalStateException if it is called after
439     * prepare() or before setOutputFormat()
440     */
441    public native void setVideoSize(int width, int height)
442            throws IllegalStateException;
443
444    /**
445     * Sets the frame rate of the video to be captured.  Must be called
446     * after setVideoSource(). Call this after setOutFormat() but before
447     * prepare().
448     *
449     * @param rate the number of frames per second of video to capture
450     * @throws IllegalStateException if it is called after
451     * prepare() or before setOutputFormat().
452     *
453     * NOTE: On some devices that have auto-frame rate, this sets the
454     * maximum frame rate, not a constant frame rate. Actual frame rate
455     * will vary according to lighting conditions.
456     */
457    public native void setVideoFrameRate(int rate) throws IllegalStateException;
458
459    /**
460     * Sets the maximum duration (in ms) of the recording session.
461     * Call this after setOutFormat() but before prepare().
462     * After recording reaches the specified duration, a notification
463     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
464     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
465     * and recording will be stopped. Stopping happens asynchronously, there
466     * is no guarantee that the recorder will have stopped by the time the
467     * listener is notified.
468     *
469     * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
470     *
471     */
472    public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
473
474    /**
475     * Sets the maximum filesize (in bytes) of the recording session.
476     * Call this after setOutFormat() but before prepare().
477     * After recording reaches the specified filesize, a notification
478     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
479     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
480     * and recording will be stopped. Stopping happens asynchronously, there
481     * is no guarantee that the recorder will have stopped by the time the
482     * listener is notified.
483     *
484     * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
485     *
486     */
487    public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
488
489    /**
490     * Sets the audio encoder to be used for recording. If this method is not
491     * called, the output file will not contain an audio track. Call this after
492     * setOutputFormat() but before prepare().
493     *
494     * @param audio_encoder the audio encoder to use.
495     * @throws IllegalStateException if it is called before
496     * setOutputFormat() or after prepare().
497     * @see android.media.MediaRecorder.AudioEncoder
498     */
499    public native void setAudioEncoder(int audio_encoder)
500            throws IllegalStateException;
501
502    /**
503     * Sets the video encoder to be used for recording. If this method is not
504     * called, the output file will not contain an video track. Call this after
505     * setOutputFormat() and before prepare().
506     *
507     * @param video_encoder the video encoder to use.
508     * @throws IllegalStateException if it is called before
509     * setOutputFormat() or after prepare()
510     * @see android.media.MediaRecorder.VideoEncoder
511     */
512    public native void setVideoEncoder(int video_encoder)
513            throws IllegalStateException;
514
515    /**
516     * Sets the audio sampling rate for recording. Call this method before prepare().
517     * Prepare() may perform additional checks on the parameter to make sure whether
518     * the specified audio sampling rate is applicable. The sampling rate really depends
519     * on the format for the audio recording, as well as the capabilities of the platform.
520     * For instance, the sampling rate supported by AAC audio coding standard ranges
521     * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
522     * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
523     * standard for the supported audio sampling rate.
524     *
525     * @param samplingRate the sampling rate for audio in samples per second.
526     */
527    public void setAudioSamplingRate(int samplingRate) {
528        if (samplingRate <= 0) {
529            throw new IllegalArgumentException("Audio sampling rate is not positive");
530        }
531        setParameter("audio-param-sampling-rate=" + samplingRate);
532    }
533
534    /**
535     * Sets the number of audio channels for recording. Call this method before prepare().
536     * Prepare() may perform additional checks on the parameter to make sure whether the
537     * specified number of audio channels are applicable.
538     *
539     * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
540     * (stereo).
541     */
542    public void setAudioChannels(int numChannels) {
543        if (numChannels <= 0) {
544            throw new IllegalArgumentException("Number of channels is not positive");
545        }
546        setParameter("audio-param-number-of-channels=" + numChannels);
547    }
548
549    /**
550     * Sets the audio encoding bit rate for recording. Call this method before prepare().
551     * Prepare() may perform additional checks on the parameter to make sure whether the
552     * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
553     * internally to ensure the audio recording can proceed smoothly based on the
554     * capabilities of the platform.
555     *
556     * @param bitRate the audio encoding bit rate in bits per second.
557     */
558    public void setAudioEncodingBitRate(int bitRate) {
559        if (bitRate <= 0) {
560            throw new IllegalArgumentException("Audio encoding bit rate is not positive");
561        }
562        setParameter("audio-param-encoding-bitrate=" + bitRate);
563    }
564
565    /**
566     * Sets the video encoding bit rate for recording. Call this method before prepare().
567     * Prepare() may perform additional checks on the parameter to make sure whether the
568     * specified bit rate is applicable, and sometimes the passed bitRate will be
569     * clipped internally to ensure the video recording can proceed smoothly based on
570     * the capabilities of the platform.
571     *
572     * @param bitRate the video encoding bit rate in bits per second.
573     */
574    public void setVideoEncodingBitRate(int bitRate) {
575        if (bitRate <= 0) {
576            throw new IllegalArgumentException("Video encoding bit rate is not positive");
577        }
578        setParameter("video-param-encoding-bitrate=" + bitRate);
579    }
580
581    /**
582     * Currently not implemented. It does nothing.
583     * @deprecated Time lapse mode video recording using camera still image capture
584     * is not desirable, and will not be supported.
585     * @hide
586     */
587    public void setAuxiliaryOutputFile(FileDescriptor fd)
588    {
589        Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
590    }
591
592    /**
593     * Currently not implemented. It does nothing.
594     * @deprecated Time lapse mode video recording using camera still image capture
595     * is not desirable, and will not be supported.
596     * @hide
597     */
598    public void setAuxiliaryOutputFile(String path)
599    {
600        Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
601    }
602
603    /**
604     * Pass in the file descriptor of the file to be written. Call this after
605     * setOutputFormat() but before prepare().
606     *
607     * @param fd an open file descriptor to be written into.
608     * @throws IllegalStateException if it is called before
609     * setOutputFormat() or after prepare()
610     */
611    public void setOutputFile(FileDescriptor fd) throws IllegalStateException
612    {
613        mPath = null;
614        mFd = fd;
615    }
616
617    /**
618     * Sets the path of the output file to be produced. Call this after
619     * setOutputFormat() but before prepare().
620     *
621     * @param path The pathname to use.
622     * @throws IllegalStateException if it is called before
623     * setOutputFormat() or after prepare()
624     */
625    public void setOutputFile(String path) throws IllegalStateException
626    {
627        mFd = null;
628        mPath = path;
629    }
630
631    // native implementation
632    private native void _setOutputFile(FileDescriptor fd, long offset, long length)
633        throws IllegalStateException, IOException;
634    private native void _prepare() throws IllegalStateException, IOException;
635
636    /**
637     * Prepares the recorder to begin capturing and encoding data. This method
638     * must be called after setting up the desired audio and video sources,
639     * encoders, file format, etc., but before start().
640     *
641     * @throws IllegalStateException if it is called after
642     * start() or before setOutputFormat().
643     * @throws IOException if prepare fails otherwise.
644     */
645    public void prepare() throws IllegalStateException, IOException
646    {
647        if (mPath != null) {
648            FileOutputStream fos = new FileOutputStream(mPath);
649            try {
650                _setOutputFile(fos.getFD(), 0, 0);
651            } finally {
652                fos.close();
653            }
654        } else if (mFd != null) {
655            _setOutputFile(mFd, 0, 0);
656        } else {
657            throw new IOException("No valid output file");
658        }
659
660        _prepare();
661    }
662
663    /**
664     * Begins capturing and encoding data to the file specified with
665     * setOutputFile(). Call this after prepare().
666     *
667     * <p>Since API level 13, if applications set a camera via
668     * {@link #setCamera(Camera)}, the apps can use the camera after this method
669     * call. The apps do not need to lock the camera again. However, if this
670     * method fails, the apps should still lock the camera back. The apps should
671     * not start another recording session during recording.
672     *
673     * @throws IllegalStateException if it is called before
674     * prepare().
675     */
676    public native void start() throws IllegalStateException;
677
678    /**
679     * Stops recording. Call this after start(). Once recording is stopped,
680     * you will have to configure it again as if it has just been constructed.
681     * Note that a RuntimeException is intentionally thrown to the
682     * application, if no valid audio/video data has been received when stop()
683     * is called. This happens if stop() is called immediately after
684     * start(). The failure lets the application take action accordingly to
685     * clean up the output file (delete the output file, for instance), since
686     * the output file is not properly constructed when this happens.
687     *
688     * @throws IllegalStateException if it is called before start()
689     */
690    public native void stop() throws IllegalStateException;
691
692    /**
693     * Restarts the MediaRecorder to its idle state. After calling
694     * this method, you will have to configure it again as if it had just been
695     * constructed.
696     */
697    public void reset() {
698        native_reset();
699
700        // make sure none of the listeners get called anymore
701        mEventHandler.removeCallbacksAndMessages(null);
702    }
703
704    private native void native_reset();
705
706    /**
707     * Returns the maximum absolute amplitude that was sampled since the last
708     * call to this method. Call this only after the setAudioSource().
709     *
710     * @return the maximum absolute amplitude measured since the last call, or
711     * 0 when called for the first time
712     * @throws IllegalStateException if it is called before
713     * the audio source has been set.
714     */
715    public native int getMaxAmplitude() throws IllegalStateException;
716
717    /* Do not change this value without updating its counterpart
718     * in include/media/mediarecorder.h!
719     */
720    /** Unspecified media recorder error.
721     * @see android.media.MediaRecorder.OnErrorListener
722     */
723    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
724
725    /**
726     * Interface definition for a callback to be invoked when an error
727     * occurs while recording.
728     */
729    public interface OnErrorListener
730    {
731        /**
732         * Called when an error occurs while recording.
733         *
734         * @param mr the MediaRecorder that encountered the error
735         * @param what    the type of error that has occurred:
736         * <ul>
737         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
738         * </ul>
739         * @param extra   an extra code, specific to the error type
740         */
741        void onError(MediaRecorder mr, int what, int extra);
742    }
743
744    /**
745     * Register a callback to be invoked when an error occurs while
746     * recording.
747     *
748     * @param l the callback that will be run
749     */
750    public void setOnErrorListener(OnErrorListener l)
751    {
752        mOnErrorListener = l;
753    }
754
755    /* Do not change these values without updating their counterparts
756     * in include/media/mediarecorder.h!
757     */
758    /** Unspecified media recorder error.
759     * @see android.media.MediaRecorder.OnInfoListener
760     */
761    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
762    /** A maximum duration had been setup and has now been reached.
763     * @see android.media.MediaRecorder.OnInfoListener
764     */
765    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
766    /** A maximum filesize had been setup and has now been reached.
767     * @see android.media.MediaRecorder.OnInfoListener
768     */
769    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
770
771    /** informational events for individual tracks, for testing purpose.
772     * The track informational event usually contains two parts in the ext1
773     * arg of the onInfo() callback: bit 31-28 contains the track id; and
774     * the rest of the 28 bits contains the informational event defined here.
775     * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
776     * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
777     * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
778     * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
779     * application should extract the track id and the type of informational
780     * event from ext1, accordingly.
781     *
782     * FIXME:
783     * Please update the comment for onInfo also when these
784     * events are unhidden so that application knows how to extract the track
785     * id and the informational event type from onInfo callback.
786     *
787     * {@hide}
788     */
789    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
790    /** Signal the completion of the track for the recording session.
791     * {@hide}
792     */
793    public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
794    /** Indicate the recording progress in time (ms) during recording.
795     * {@hide}
796     */
797    public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
798    /** Indicate the track type: 0 for Audio and 1 for Video.
799     * {@hide}
800     */
801    public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
802    /** Provide the track duration information.
803     * {@hide}
804     */
805    public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
806    /** Provide the max chunk duration in time (ms) for the given track.
807     * {@hide}
808     */
809    public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
810    /** Provide the total number of recordd frames.
811     * {@hide}
812     */
813    public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
814    /** Provide the max spacing between neighboring chunks for the given track.
815     * {@hide}
816     */
817    public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
818    /** Provide the elapsed time measuring from the start of the recording
819     * till the first output frame of the given track is received, excluding
820     * any intentional start time offset of a recording session for the
821     * purpose of eliminating the recording sound in the recorded file.
822     * {@hide}
823     */
824    public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
825    /** Provide the start time difference (delay) betweeen this track and
826     * the start of the movie.
827     * {@hide}
828     */
829    public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
830    /** Provide the total number of data (in kilo-bytes) encoded.
831     * {@hide}
832     */
833    public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
834    /**
835     * {@hide}
836     */
837    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
838
839
840    /**
841     * Interface definition for a callback to be invoked when an error
842     * occurs while recording.
843     */
844    public interface OnInfoListener
845    {
846        /**
847         * Called when an error occurs while recording.
848         *
849         * @param mr the MediaRecorder that encountered the error
850         * @param what    the type of error that has occurred:
851         * <ul>
852         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
853         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
854         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
855         * </ul>
856         * @param extra   an extra code, specific to the error type
857         */
858        void onInfo(MediaRecorder mr, int what, int extra);
859    }
860
861    /**
862     * Register a callback to be invoked when an informational event occurs while
863     * recording.
864     *
865     * @param listener the callback that will be run
866     */
867    public void setOnInfoListener(OnInfoListener listener)
868    {
869        mOnInfoListener = listener;
870    }
871
872    private class EventHandler extends Handler
873    {
874        private MediaRecorder mMediaRecorder;
875
876        public EventHandler(MediaRecorder mr, Looper looper) {
877            super(looper);
878            mMediaRecorder = mr;
879        }
880
881        /* Do not change these values without updating their counterparts
882         * in include/media/mediarecorder.h!
883         */
884        private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
885        private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
886        private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
887        private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
888
889        /* Events related to individual tracks */
890        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
891        private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
892        private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
893        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
894
895
896        @Override
897        public void handleMessage(Message msg) {
898            if (mMediaRecorder.mNativeContext == 0) {
899                Log.w(TAG, "mediarecorder went away with unhandled events");
900                return;
901            }
902            switch(msg.what) {
903            case MEDIA_RECORDER_EVENT_ERROR:
904            case MEDIA_RECORDER_TRACK_EVENT_ERROR:
905                if (mOnErrorListener != null)
906                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
907
908                return;
909
910            case MEDIA_RECORDER_EVENT_INFO:
911            case MEDIA_RECORDER_TRACK_EVENT_INFO:
912                if (mOnInfoListener != null)
913                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
914
915                return;
916
917            default:
918                Log.e(TAG, "Unknown message type " + msg.what);
919                return;
920            }
921        }
922    }
923
924    /**
925     * Called from native code when an interesting event happens.  This method
926     * just uses the EventHandler system to post the event back to the main app thread.
927     * We use a weak reference to the original MediaRecorder object so that the native
928     * code is safe from the object disappearing from underneath it.  (This is
929     * the cookie passed to native_setup().)
930     */
931    private static void postEventFromNative(Object mediarecorder_ref,
932                                            int what, int arg1, int arg2, Object obj)
933    {
934        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
935        if (mr == null) {
936            return;
937        }
938
939        if (mr.mEventHandler != null) {
940            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
941            mr.mEventHandler.sendMessage(m);
942        }
943    }
944
945    /**
946     * Releases resources associated with this MediaRecorder object.
947     * It is good practice to call this method when you're done
948     * using the MediaRecorder. In particular, whenever an Activity
949     * of an application is paused (its onPause() method is called),
950     * or stopped (its onStop() method is called), this method should be
951     * invoked to release the MediaRecorder object, unless the application
952     * has a special need to keep the object around. In addition to
953     * unnecessary resources (such as memory and instances of codecs)
954     * being held, failure to call this method immediately if a
955     * MediaRecorder object is no longer needed may also lead to
956     * continuous battery consumption for mobile devices, and recording
957     * failure for other applications if no multiple instances of the
958     * same codec are supported on a device. Even if multiple instances
959     * of the same codec are supported, some performance degradation
960     * may be expected when unnecessary multiple instances are used
961     * at the same time.
962     */
963    public native void release();
964
965    private static native final void native_init();
966
967    private native final void native_setup(Object mediarecorder_this) throws IllegalStateException;
968
969    private native final void native_finalize();
970
971    private native void setParameter(String nameValuePair);
972
973    @Override
974    protected void finalize() { native_finalize(); }
975}
976