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