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