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