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