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