MediaRecorder.java revision 528b084be26ff6f5b5d8cf42007bf964857be8da
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>See the <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a>
64 * documentation for additional help with using MediaRecorder.
65 * <p>Note: Currently, MediaRecorder does not work on the emulator.
66 */
67public class MediaRecorder
68{
69    static {
70        System.loadLibrary("media_jni");
71        native_init();
72    }
73    private final static String TAG = "MediaRecorder";
74
75    // The two fields below are accessed by native methods
76    @SuppressWarnings("unused")
77    private int mNativeContext;
78
79    @SuppressWarnings("unused")
80    private Surface mSurface;
81
82    private String mPath;
83    private FileDescriptor mFd;
84    private boolean mPrepareAuxiliaryFile = false;
85    private String mPathAux;
86    private FileDescriptor mFdAux;
87    private EventHandler mEventHandler;
88    private OnErrorListener mOnErrorListener;
89    private OnInfoListener mOnInfoListener;
90
91    /**
92     * Default constructor.
93     */
94    public MediaRecorder() {
95
96        Looper looper;
97        if ((looper = Looper.myLooper()) != null) {
98            mEventHandler = new EventHandler(this, looper);
99        } else if ((looper = Looper.getMainLooper()) != null) {
100            mEventHandler = new EventHandler(this, looper);
101        } else {
102            mEventHandler = null;
103        }
104
105        /* Native setup requires a weak reference to our object.
106         * It's easier to create it here than in C++.
107         */
108        native_setup(new WeakReference<MediaRecorder>(this));
109    }
110
111    /**
112     * Sets a Camera to use for recording. Use this function to switch
113     * quickly between preview and capture mode without a teardown of
114     * the camera object. {@link android.hardware.Camera#unlock()} should be
115     * called before this. 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     * <p>Since API level 13, if applications set a camera via
722     * {@link #setCamera(Camera)}, the apps can use the camera after this method
723     * call. The apps do not need to lock the camera again. However, if this
724     * method fails, the apps should still lock the camera back. The apps should
725     * not start another recording session during recording.
726     *
727     * @throws IllegalStateException if it is called before
728     * prepare().
729     */
730    public native void start() throws IllegalStateException;
731
732    /**
733     * Stops recording. Call this after start(). Once recording is stopped,
734     * you will have to configure it again as if it has just been constructed.
735     * Note that a RuntimeException is intentionally thrown to the
736     * application, if no valid audio/video data has been received when stop()
737     * is called. This happens if stop() is called immediately after
738     * start(). The failure lets the application take action accordingly to
739     * clean up the output file (delete the output file, for instance), since
740     * the output file is not properly constructed when this happens.
741     *
742     * @throws IllegalStateException if it is called before start()
743     */
744    public native void stop() throws IllegalStateException;
745
746    /**
747     * Restarts the MediaRecorder to its idle state. After calling
748     * this method, you will have to configure it again as if it had just been
749     * constructed.
750     */
751    public void reset() {
752        native_reset();
753
754        // make sure none of the listeners get called anymore
755        mEventHandler.removeCallbacksAndMessages(null);
756    }
757
758    private native void native_reset();
759
760    /**
761     * Returns the maximum absolute amplitude that was sampled since the last
762     * call to this method. Call this only after the setAudioSource().
763     *
764     * @return the maximum absolute amplitude measured since the last call, or
765     * 0 when called for the first time
766     * @throws IllegalStateException if it is called before
767     * the audio source has been set.
768     */
769    public native int getMaxAmplitude() throws IllegalStateException;
770
771    /* Do not change this value without updating its counterpart
772     * in include/media/mediarecorder.h!
773     */
774    /** Unspecified media recorder error.
775     * @see android.media.MediaRecorder.OnErrorListener
776     */
777    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
778
779    /**
780     * Interface definition for a callback to be invoked when an error
781     * occurs while recording.
782     */
783    public interface OnErrorListener
784    {
785        /**
786         * Called when an error occurs while recording.
787         *
788         * @param mr the MediaRecorder that encountered the error
789         * @param what    the type of error that has occurred:
790         * <ul>
791         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
792         * </ul>
793         * @param extra   an extra code, specific to the error type
794         */
795        void onError(MediaRecorder mr, int what, int extra);
796    }
797
798    /**
799     * Register a callback to be invoked when an error occurs while
800     * recording.
801     *
802     * @param l the callback that will be run
803     */
804    public void setOnErrorListener(OnErrorListener l)
805    {
806        mOnErrorListener = l;
807    }
808
809    /* Do not change these values without updating their counterparts
810     * in include/media/mediarecorder.h!
811     */
812    /** Unspecified media recorder error.
813     * @see android.media.MediaRecorder.OnInfoListener
814     */
815    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
816    /** A maximum duration had been setup and has now been reached.
817     * @see android.media.MediaRecorder.OnInfoListener
818     */
819    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
820    /** A maximum filesize had been setup and has now been reached.
821     * @see android.media.MediaRecorder.OnInfoListener
822     */
823    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
824
825    /** informational events for individual tracks, for testing purpose.
826     * The track informational event usually contains two parts in the ext1
827     * arg of the onInfo() callback: bit 31-28 contains the track id; and
828     * the rest of the 28 bits contains the informational event defined here.
829     * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
830     * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
831     * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
832     * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
833     * application should extract the track id and the type of informational
834     * event from ext1, accordingly.
835     *
836     * FIXME:
837     * Please update the comment for onInfo also when these
838     * events are unhidden so that application knows how to extract the track
839     * id and the informational event type from onInfo callback.
840     *
841     * {@hide}
842     */
843    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
844    /** Signal the completion of the track for the recording session.
845     * {@hide}
846     */
847    public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
848    /** Indicate the recording progress in time (ms) during recording.
849     * {@hide}
850     */
851    public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
852    /** Indicate the track type: 0 for Audio and 1 for Video.
853     * {@hide}
854     */
855    public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
856    /** Provide the track duration information.
857     * {@hide}
858     */
859    public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
860    /** Provide the max chunk duration in time (ms) for the given track.
861     * {@hide}
862     */
863    public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
864    /** Provide the total number of recordd frames.
865     * {@hide}
866     */
867    public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
868    /** Provide the max spacing between neighboring chunks for the given track.
869     * {@hide}
870     */
871    public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
872    /** Provide the elapsed time measuring from the start of the recording
873     * till the first output frame of the given track is received, excluding
874     * any intentional start time offset of a recording session for the
875     * purpose of eliminating the recording sound in the recorded file.
876     * {@hide}
877     */
878    public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
879    /** Provide the start time difference (delay) betweeen this track and
880     * the start of the movie.
881     * {@hide}
882     */
883    public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
884    /** Provide the total number of data (in kilo-bytes) encoded.
885     * {@hide}
886     */
887    public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
888    /**
889     * {@hide}
890     */
891    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
892
893
894    /**
895     * Interface definition for a callback to be invoked when an error
896     * occurs while recording.
897     */
898    public interface OnInfoListener
899    {
900        /**
901         * Called when an error occurs while recording.
902         *
903         * @param mr the MediaRecorder that encountered the error
904         * @param what    the type of error that has occurred:
905         * <ul>
906         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
907         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
908         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
909         * </ul>
910         * @param extra   an extra code, specific to the error type
911         */
912        void onInfo(MediaRecorder mr, int what, int extra);
913    }
914
915    /**
916     * Register a callback to be invoked when an informational event occurs while
917     * recording.
918     *
919     * @param listener the callback that will be run
920     */
921    public void setOnInfoListener(OnInfoListener listener)
922    {
923        mOnInfoListener = listener;
924    }
925
926    private class EventHandler extends Handler
927    {
928        private MediaRecorder mMediaRecorder;
929
930        public EventHandler(MediaRecorder mr, Looper looper) {
931            super(looper);
932            mMediaRecorder = mr;
933        }
934
935        /* Do not change these values without updating their counterparts
936         * in include/media/mediarecorder.h!
937         */
938        private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
939        private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
940        private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
941        private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
942
943        /* Events related to individual tracks */
944        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
945        private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
946        private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
947        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
948
949
950        @Override
951        public void handleMessage(Message msg) {
952            if (mMediaRecorder.mNativeContext == 0) {
953                Log.w(TAG, "mediarecorder went away with unhandled events");
954                return;
955            }
956            switch(msg.what) {
957            case MEDIA_RECORDER_EVENT_ERROR:
958            case MEDIA_RECORDER_TRACK_EVENT_ERROR:
959                if (mOnErrorListener != null)
960                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
961
962                return;
963
964            case MEDIA_RECORDER_EVENT_INFO:
965            case MEDIA_RECORDER_TRACK_EVENT_INFO:
966                if (mOnInfoListener != null)
967                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
968
969                return;
970
971            default:
972                Log.e(TAG, "Unknown message type " + msg.what);
973                return;
974            }
975        }
976    }
977
978    /**
979     * Called from native code when an interesting event happens.  This method
980     * just uses the EventHandler system to post the event back to the main app thread.
981     * We use a weak reference to the original MediaRecorder object so that the native
982     * code is safe from the object disappearing from underneath it.  (This is
983     * the cookie passed to native_setup().)
984     */
985    private static void postEventFromNative(Object mediarecorder_ref,
986                                            int what, int arg1, int arg2, Object obj)
987    {
988        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
989        if (mr == null) {
990            return;
991        }
992
993        if (mr.mEventHandler != null) {
994            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
995            mr.mEventHandler.sendMessage(m);
996        }
997    }
998
999    /**
1000     * Releases resources associated with this MediaRecorder object.
1001     * It is good practice to call this method when you're done
1002     * using the MediaRecorder.
1003     */
1004    public native void release();
1005
1006    private static native final void native_init();
1007
1008    private native final void native_setup(Object mediarecorder_this) throws IllegalStateException;
1009
1010    private native final void native_finalize();
1011
1012    private native void setParameter(String nameValuePair);
1013
1014    @Override
1015    protected void finalize() { native_finalize(); }
1016}
1017