MediaRecorder.java revision e176ee1222931d67aaea0a3df96262728cc31031
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         * <p>
211         * Capturing from <code>VOICE_UPLINK</code> source requires the
212         * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
213         * This permission is reserved for use by system components and is not available to
214         * third-party applications.
215         * </p>
216         */
217        public static final int VOICE_UPLINK = 2;
218
219        /** Voice call downlink (Rx) audio source.
220         * <p>
221         * Capturing from <code>VOICE_DOWNLINK</code> source requires the
222         * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
223         * This permission is reserved for use by system components and is not available to
224         * third-party applications.
225         * </p>
226         */
227        public static final int VOICE_DOWNLINK = 3;
228
229        /** Voice call uplink + downlink audio source
230         * <p>
231         * Capturing from <code>VOICE_CALL</code> source requires the
232         * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
233         * This permission is reserved for use by system components and is not available to
234         * third-party applications.
235         * </p>
236         */
237        public static final int VOICE_CALL = 4;
238
239        /** Microphone audio source tuned for video recording, with the same orientation
240         *  as the camera if available. */
241        public static final int CAMCORDER = 5;
242
243        /** Microphone audio source tuned for voice recognition. */
244        public static final int VOICE_RECOGNITION = 6;
245
246        /** Microphone audio source tuned for voice communications such as VoIP. It
247         *  will for instance take advantage of echo cancellation or automatic gain control
248         *  if available.
249         */
250        public static final int VOICE_COMMUNICATION = 7;
251
252        /**
253         * Audio source for a submix of audio streams to be presented remotely.
254         * <p>
255         * An application can use this audio source to capture a mix of audio streams
256         * that should be transmitted to a remote receiver such as a Wifi display.
257         * While recording is active, these audio streams are redirected to the remote
258         * submix instead of being played on the device speaker or headset.
259         * </p><p>
260         * Certain streams are excluded from the remote submix, including
261         * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_ALARM},
262         * and {@link AudioManager#STREAM_NOTIFICATION}.  These streams will continue
263         * to be presented locally as usual.
264         * </p><p>
265         * Capturing the remote submix audio requires the
266         * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
267         * This permission is reserved for use by system components and is not available to
268         * third-party applications.
269         * </p>
270         */
271        public static final int REMOTE_SUBMIX = 8;
272
273        /** Microphone audio source tuned for unprocessed (raw) sound if available, behaves like
274         *  {@link #DEFAULT} otherwise. */
275        public static final int UNPROCESSED = 9;
276
277        /**
278         * Audio source for capturing broadcast radio tuner output.
279         * @hide
280         */
281        @SystemApi
282        public static final int RADIO_TUNER = 1998;
283
284        /**
285         * Audio source for preemptible, low-priority software hotword detection
286         * It presents the same gain and pre processing tuning as {@link #VOICE_RECOGNITION}.
287         * <p>
288         * An application should use this audio source when it wishes to do
289         * always-on software hotword detection, while gracefully giving in to any other application
290         * that might want to read from the microphone.
291         * </p>
292         * This is a hidden audio source.
293         * @hide
294         */
295        @SystemApi
296        public static final int HOTWORD = 1999;
297    }
298
299    // TODO make AudioSource static (API change) and move this method inside the AudioSource class
300    /**
301     * @hide
302     * @param source An audio source to test
303     * @return true if the source is only visible to system components
304     */
305    public static boolean isSystemOnlyAudioSource(int source) {
306        switch(source) {
307        case AudioSource.DEFAULT:
308        case AudioSource.MIC:
309        case AudioSource.VOICE_UPLINK:
310        case AudioSource.VOICE_DOWNLINK:
311        case AudioSource.VOICE_CALL:
312        case AudioSource.CAMCORDER:
313        case AudioSource.VOICE_RECOGNITION:
314        case AudioSource.VOICE_COMMUNICATION:
315        //case REMOTE_SUBMIX:  considered "system" as it requires system permissions
316        case AudioSource.UNPROCESSED:
317            return false;
318        default:
319            return true;
320        }
321    }
322
323    /**
324     * Defines the video source. These constants are used with
325     * {@link MediaRecorder#setVideoSource(int)}.
326     */
327    public final class VideoSource {
328      /* Do not change these values without updating their counterparts
329       * in include/media/mediarecorder.h!
330       */
331        private VideoSource() {}
332        public static final int DEFAULT = 0;
333        /** Camera video source
334         * <p>
335         * Using the {@link android.hardware.Camera} API as video source.
336         * </p>
337         */
338        public static final int CAMERA = 1;
339        /** Surface video source
340         * <p>
341         * Using a Surface as video source.
342         * </p><p>
343         * This flag must be used when recording from an
344         * {@link android.hardware.camera2} API source.
345         * </p><p>
346         * When using this video source type, use {@link MediaRecorder#getSurface()}
347         * to retrieve the surface created by MediaRecorder.
348         */
349        public static final int SURFACE = 2;
350    }
351
352    /**
353     * Defines the output format. These constants are used with
354     * {@link MediaRecorder#setOutputFormat(int)}.
355     */
356    public final class OutputFormat {
357      /* Do not change these values without updating their counterparts
358       * in include/media/mediarecorder.h!
359       */
360        private OutputFormat() {}
361        public static final int DEFAULT = 0;
362        /** 3GPP media file format*/
363        public static final int THREE_GPP = 1;
364        /** MPEG4 media file format*/
365        public static final int MPEG_4 = 2;
366
367        /** The following formats are audio only .aac or .amr formats */
368
369        /**
370         * AMR NB file format
371         * @deprecated  Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
372         */
373        public static final int RAW_AMR = 3;
374
375        /** AMR NB file format */
376        public static final int AMR_NB = 3;
377
378        /** AMR WB file format */
379        public static final int AMR_WB = 4;
380
381        /** @hide AAC ADIF file format */
382        public static final int AAC_ADIF = 5;
383
384        /** AAC ADTS file format */
385        public static final int AAC_ADTS = 6;
386
387        /** @hide Stream over a socket, limited to a single stream */
388        public static final int OUTPUT_FORMAT_RTP_AVP = 7;
389
390        /** H.264/AAC data encapsulated in MPEG2/TS */
391        public static final int MPEG_2_TS = 8;
392
393        /** VP8/VORBIS data in a WEBM container */
394        public static final int WEBM = 9;
395    };
396
397    /**
398     * Defines the audio encoding. These constants are used with
399     * {@link MediaRecorder#setAudioEncoder(int)}.
400     */
401    public final class AudioEncoder {
402      /* Do not change these values without updating their counterparts
403       * in include/media/mediarecorder.h!
404       */
405        private AudioEncoder() {}
406        public static final int DEFAULT = 0;
407        /** AMR (Narrowband) audio codec */
408        public static final int AMR_NB = 1;
409        /** AMR (Wideband) audio codec */
410        public static final int AMR_WB = 2;
411        /** AAC Low Complexity (AAC-LC) audio codec */
412        public static final int AAC = 3;
413        /** High Efficiency AAC (HE-AAC) audio codec */
414        public static final int HE_AAC = 4;
415        /** Enhanced Low Delay AAC (AAC-ELD) audio codec */
416        public static final int AAC_ELD = 5;
417        /** Ogg Vorbis audio codec */
418        public static final int VORBIS = 6;
419    }
420
421    /**
422     * Defines the video encoding. These constants are used with
423     * {@link MediaRecorder#setVideoEncoder(int)}.
424     */
425    public final class VideoEncoder {
426      /* Do not change these values without updating their counterparts
427       * in include/media/mediarecorder.h!
428       */
429        private VideoEncoder() {}
430        public static final int DEFAULT = 0;
431        public static final int H263 = 1;
432        public static final int H264 = 2;
433        public static final int MPEG_4_SP = 3;
434        public static final int VP8 = 4;
435        public static final int HEVC = 5;
436    }
437
438    /**
439     * Sets the audio source to be used for recording. If this method is not
440     * called, the output file will not contain an audio track. The source needs
441     * to be specified before setting recording-parameters or encoders. Call
442     * this only before setOutputFormat().
443     *
444     * @param audio_source the audio source to use
445     * @throws IllegalStateException if it is called after setOutputFormat()
446     * @see android.media.MediaRecorder.AudioSource
447     */
448    public native void setAudioSource(int audio_source)
449            throws IllegalStateException;
450
451    /**
452     * Gets the maximum value for audio sources.
453     * @see android.media.MediaRecorder.AudioSource
454     */
455    public static final int getAudioSourceMax() {
456        return AudioSource.UNPROCESSED;
457    }
458
459    /**
460     * Sets the video source to be used for recording. If this method is not
461     * called, the output file will not contain an video track. The source needs
462     * to be specified before setting recording-parameters or encoders. Call
463     * this only before setOutputFormat().
464     *
465     * @param video_source the video source to use
466     * @throws IllegalStateException if it is called after setOutputFormat()
467     * @see android.media.MediaRecorder.VideoSource
468     */
469    public native void setVideoSource(int video_source)
470            throws IllegalStateException;
471
472    /**
473     * Uses the settings from a CamcorderProfile object for recording. This method should
474     * be called after the video AND audio sources are set, and before setOutputFile().
475     * If a time lapse CamcorderProfile is used, audio related source or recording
476     * parameters are ignored.
477     *
478     * @param profile the CamcorderProfile to use
479     * @see android.media.CamcorderProfile
480     */
481    public void setProfile(CamcorderProfile profile) {
482        setOutputFormat(profile.fileFormat);
483        setVideoFrameRate(profile.videoFrameRate);
484        setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
485        setVideoEncodingBitRate(profile.videoBitRate);
486        setVideoEncoder(profile.videoCodec);
487        if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW &&
488             profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) {
489            // Nothing needs to be done. Call to setCaptureRate() enables
490            // time lapse video recording.
491        } else {
492            setAudioEncodingBitRate(profile.audioBitRate);
493            setAudioChannels(profile.audioChannels);
494            setAudioSamplingRate(profile.audioSampleRate);
495            setAudioEncoder(profile.audioCodec);
496        }
497    }
498
499    /**
500     * Set video frame capture rate. This can be used to set a different video frame capture
501     * rate than the recorded video's playback rate. This method also sets the recording mode
502     * to time lapse. In time lapse video recording, only video is recorded. Audio related
503     * parameters are ignored when a time lapse recording session starts, if an application
504     * sets them.
505     *
506     * @param fps Rate at which frames should be captured in frames per second.
507     * The fps can go as low as desired. However the fastest fps will be limited by the hardware.
508     * For resolutions that can be captured by the video camera, the fastest fps can be computed using
509     * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher
510     * resolutions the fastest fps may be more restrictive.
511     * Note that the recorder cannot guarantee that frames will be captured at the
512     * given rate due to camera/encoder limitations. However it tries to be as close as
513     * possible.
514     */
515    public void setCaptureRate(double fps) {
516        // Make sure that time lapse is enabled when this method is called.
517        setParameter("time-lapse-enable=1");
518        setParameter("time-lapse-fps=" + fps);
519    }
520
521    /**
522     * Sets the orientation hint for output video playback.
523     * This method should be called before prepare(). This method will not
524     * trigger the source video frame to rotate during video recording, but to
525     * add a composition matrix containing the rotation angle in the output
526     * video if the output format is OutputFormat.THREE_GPP or
527     * OutputFormat.MPEG_4 so that a video player can choose the proper
528     * orientation for playback. Note that some video players may choose
529     * to ignore the compostion matrix in a video during playback.
530     *
531     * @param degrees the angle to be rotated clockwise in degrees.
532     * The supported angles are 0, 90, 180, and 270 degrees.
533     * @throws IllegalArgumentException if the angle is not supported.
534     *
535     */
536    public void setOrientationHint(int degrees) {
537        if (degrees != 0   &&
538            degrees != 90  &&
539            degrees != 180 &&
540            degrees != 270) {
541            throw new IllegalArgumentException("Unsupported angle: " + degrees);
542        }
543        setParameter("video-param-rotation-angle-degrees=" + degrees);
544    }
545
546    /**
547     * Set and store the geodata (latitude and longitude) in the output file.
548     * This method should be called before prepare(). The geodata is
549     * stored in udta box if the output format is OutputFormat.THREE_GPP
550     * or OutputFormat.MPEG_4, and is ignored for other output formats.
551     * The geodata is stored according to ISO-6709 standard.
552     *
553     * @param latitude latitude in degrees. Its value must be in the
554     * range [-90, 90].
555     * @param longitude longitude in degrees. Its value must be in the
556     * range [-180, 180].
557     *
558     * @throws IllegalArgumentException if the given latitude or
559     * longitude is out of range.
560     *
561     */
562    public void setLocation(float latitude, float longitude) {
563        int latitudex10000  = (int) (latitude * 10000 + 0.5);
564        int longitudex10000 = (int) (longitude * 10000 + 0.5);
565
566        if (latitudex10000 > 900000 || latitudex10000 < -900000) {
567            String msg = "Latitude: " + latitude + " out of range.";
568            throw new IllegalArgumentException(msg);
569        }
570        if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
571            String msg = "Longitude: " + longitude + " out of range";
572            throw new IllegalArgumentException(msg);
573        }
574
575        setParameter("param-geotag-latitude=" + latitudex10000);
576        setParameter("param-geotag-longitude=" + longitudex10000);
577    }
578
579    /**
580     * Sets the format of the output file produced during recording. Call this
581     * after setAudioSource()/setVideoSource() but before prepare().
582     *
583     * <p>It is recommended to always use 3GP format when using the H.263
584     * video encoder and AMR audio encoder. Using an MPEG-4 container format
585     * may confuse some desktop players.</p>
586     *
587     * @param output_format the output format to use. The output format
588     * needs to be specified before setting recording-parameters or encoders.
589     * @throws IllegalStateException if it is called after prepare() or before
590     * setAudioSource()/setVideoSource().
591     * @see android.media.MediaRecorder.OutputFormat
592     */
593    public native void setOutputFormat(int output_format)
594            throws IllegalStateException;
595
596    /**
597     * Sets the width and height of the video to be captured.  Must be called
598     * after setVideoSource(). Call this after setOutFormat() but before
599     * prepare().
600     *
601     * @param width the width of the video to be captured
602     * @param height the height of the video to be captured
603     * @throws IllegalStateException if it is called after
604     * prepare() or before setOutputFormat()
605     */
606    public native void setVideoSize(int width, int height)
607            throws IllegalStateException;
608
609    /**
610     * Sets the frame rate of the video to be captured.  Must be called
611     * after setVideoSource(). Call this after setOutFormat() but before
612     * prepare().
613     *
614     * @param rate the number of frames per second of video to capture
615     * @throws IllegalStateException if it is called after
616     * prepare() or before setOutputFormat().
617     *
618     * NOTE: On some devices that have auto-frame rate, this sets the
619     * maximum frame rate, not a constant frame rate. Actual frame rate
620     * will vary according to lighting conditions.
621     */
622    public native void setVideoFrameRate(int rate) throws IllegalStateException;
623
624    /**
625     * Sets the maximum duration (in ms) of the recording session.
626     * Call this after setOutFormat() but before prepare().
627     * After recording reaches the specified duration, a notification
628     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
629     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
630     * and recording will be stopped. Stopping happens asynchronously, there
631     * is no guarantee that the recorder will have stopped by the time the
632     * listener is notified.
633     *
634     * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
635     *
636     */
637    public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
638
639    /**
640     * Sets the maximum filesize (in bytes) of the recording session.
641     * Call this after setOutFormat() but before prepare().
642     * After recording reaches the specified filesize, a notification
643     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
644     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
645     * and recording will be stopped. Stopping happens asynchronously, there
646     * is no guarantee that the recorder will have stopped by the time the
647     * listener is notified.
648     *
649     * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
650     *
651     */
652    public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
653
654    /**
655     * Sets the audio encoder to be used for recording. If this method is not
656     * called, the output file will not contain an audio track. Call this after
657     * setOutputFormat() but before prepare().
658     *
659     * @param audio_encoder the audio encoder to use.
660     * @throws IllegalStateException if it is called before
661     * setOutputFormat() or after prepare().
662     * @see android.media.MediaRecorder.AudioEncoder
663     */
664    public native void setAudioEncoder(int audio_encoder)
665            throws IllegalStateException;
666
667    /**
668     * Sets the video encoder to be used for recording. If this method is not
669     * called, the output file will not contain an video track. Call this after
670     * setOutputFormat() and before prepare().
671     *
672     * @param video_encoder the video encoder to use.
673     * @throws IllegalStateException if it is called before
674     * setOutputFormat() or after prepare()
675     * @see android.media.MediaRecorder.VideoEncoder
676     */
677    public native void setVideoEncoder(int video_encoder)
678            throws IllegalStateException;
679
680    /**
681     * Sets the audio sampling rate for recording. Call this method before prepare().
682     * Prepare() may perform additional checks on the parameter to make sure whether
683     * the specified audio sampling rate is applicable. The sampling rate really depends
684     * on the format for the audio recording, as well as the capabilities of the platform.
685     * For instance, the sampling rate supported by AAC audio coding standard ranges
686     * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
687     * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
688     * standard for the supported audio sampling rate.
689     *
690     * @param samplingRate the sampling rate for audio in samples per second.
691     */
692    public void setAudioSamplingRate(int samplingRate) {
693        if (samplingRate <= 0) {
694            throw new IllegalArgumentException("Audio sampling rate is not positive");
695        }
696        setParameter("audio-param-sampling-rate=" + samplingRate);
697    }
698
699    /**
700     * Sets the number of audio channels for recording. Call this method before prepare().
701     * Prepare() may perform additional checks on the parameter to make sure whether the
702     * specified number of audio channels are applicable.
703     *
704     * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
705     * (stereo).
706     */
707    public void setAudioChannels(int numChannels) {
708        if (numChannels <= 0) {
709            throw new IllegalArgumentException("Number of channels is not positive");
710        }
711        setParameter("audio-param-number-of-channels=" + numChannels);
712    }
713
714    /**
715     * Sets the audio encoding bit rate for recording. Call this method before prepare().
716     * Prepare() may perform additional checks on the parameter to make sure whether the
717     * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
718     * internally to ensure the audio recording can proceed smoothly based on the
719     * capabilities of the platform.
720     *
721     * @param bitRate the audio encoding bit rate in bits per second.
722     */
723    public void setAudioEncodingBitRate(int bitRate) {
724        if (bitRate <= 0) {
725            throw new IllegalArgumentException("Audio encoding bit rate is not positive");
726        }
727        setParameter("audio-param-encoding-bitrate=" + bitRate);
728    }
729
730    /**
731     * Sets the video encoding bit rate for recording. Call this method before prepare().
732     * Prepare() may perform additional checks on the parameter to make sure whether the
733     * specified bit rate is applicable, and sometimes the passed bitRate will be
734     * clipped internally to ensure the video recording can proceed smoothly based on
735     * the capabilities of the platform.
736     *
737     * @param bitRate the video encoding bit rate in bits per second.
738     */
739    public void setVideoEncodingBitRate(int bitRate) {
740        if (bitRate <= 0) {
741            throw new IllegalArgumentException("Video encoding bit rate is not positive");
742        }
743        setParameter("video-param-encoding-bitrate=" + bitRate);
744    }
745
746    /**
747     * Sets the video encoding profile for recording. Call this method before prepare().
748     * Prepare() may perform additional checks on the parameter to make sure whether the
749     * specified profile and level are applicable, and sometimes the passed profile or
750     * level will be discarded due to codec capablity or to ensure the video recording
751     * can proceed smoothly based on the capabilities of the platform.
752     * @hide
753     * @param profile declared in {@link MediaCodecInfo.CodecProfileLevel}.
754     * @param level declared in {@link MediaCodecInfo.CodecProfileLevel}.
755     */
756    public void setVideoEncodingProfileLevel(int profile, int level) {
757        if (profile <= 0)  {
758            throw new IllegalArgumentException("Video encoding profile is not positive");
759        }
760        if (level <= 0)  {
761            throw new IllegalArgumentException("Video encoding level is not positive");
762        }
763        setParameter("video-param-encoder-profile=" + profile);
764        setParameter("video-param-encoder-level=" + level);
765    }
766
767    /**
768     * Currently not implemented. It does nothing.
769     * @deprecated Time lapse mode video recording using camera still image capture
770     * is not desirable, and will not be supported.
771     * @hide
772     */
773    public void setAuxiliaryOutputFile(FileDescriptor fd)
774    {
775        Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
776    }
777
778    /**
779     * Currently not implemented. It does nothing.
780     * @deprecated Time lapse mode video recording using camera still image capture
781     * is not desirable, and will not be supported.
782     * @hide
783     */
784    public void setAuxiliaryOutputFile(String path)
785    {
786        Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
787    }
788
789    /**
790     * Pass in the file descriptor of the file to be written. Call this after
791     * setOutputFormat() but before prepare().
792     *
793     * @param fd an open file descriptor to be written into.
794     * @throws IllegalStateException if it is called before
795     * setOutputFormat() or after prepare()
796     */
797    public void setOutputFile(FileDescriptor fd) throws IllegalStateException
798    {
799        mPath = null;
800        mFd = fd;
801    }
802
803    /**
804     * Sets the next output file descriptor to be used when the maximum filesize is reached
805     * on the prior output {@link #setOutputFile} or {@link #setNextOutputFile}). File descriptor
806     * must be seekable and in read-write mode. After setting the next output file, application
807     * should not use the file referenced by this file descriptor until {@link #stop}. Application
808     * must call this after receiving on the {@link android.media.MediaRecorder.OnInfoListener} a
809     * "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING} and before receiving
810     * a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}. The file is not used
811     * until switching to that output. Application will receive
812     * {@link #MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED} when the next output file is used.
813     * Application will not be able to set a new output file if the previous one has not been used.
814     * Application is responsible for cleaning up unused files after {@link #stop} is called.
815     *
816     * @param fd an open file descriptor to be written into.
817     * @throws IllegalStateException if it is called before prepare().
818     * @throws IOException if setNextOutputFile fails otherwise.
819     */
820    public void setNextOutputFile(FileDescriptor fd) throws IllegalStateException, IOException
821    {
822        _setNextOutputFile(fd);
823    }
824
825    /**
826     * Sets the path of the output file to be produced. Call this after
827     * setOutputFormat() but before prepare().
828     *
829     * @param path The pathname to use.
830     * @throws IllegalStateException if it is called before
831     * setOutputFormat() or after prepare()
832     */
833    public void setOutputFile(String path) throws IllegalStateException
834    {
835        mFd = null;
836        mPath = path;
837    }
838
839    /**
840     * Sets the next output file path to be used when the maximum filesize is reached
841     * on the prior output {@link #setOutputFile} or {@link #setNextOutputFile}). File should
842     * be seekable. After setting the next output file, application should not use the file
843     * referenced by this file descriptor until {@link #stop}. Application must call this
844     * after receiving on the {@link android.media.MediaRecorder.OnInfoListener} a "what" code of
845     * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING} and before receiving a "what" code of
846     * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}. The file is not used until switching to
847     * that output. Application will receive {@link #MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED}
848     * when the next output file is used. Application will not be able to set a new output file if
849     * the previous one has not been used. Application is responsible for cleaning up unused files
850     * after {@link #stop} is called.
851     *
852     * @param  path The pathname to use.
853     * @throws IllegalStateException if it is called before prepare().
854     * @throws IOException if setNextOutputFile fails otherwise.
855     */
856    public void setNextOutputFile(String path) throws IllegalStateException, IOException
857    {
858        if (path != null) {
859            RandomAccessFile file = new RandomAccessFile(path, "rws");
860            try {
861                _setNextOutputFile(file.getFD());
862            } finally {
863                file.close();
864            }
865        }
866    }
867
868    // native implementation
869    private native void _setOutputFile(FileDescriptor fd) throws IllegalStateException, IOException;
870    private native void _setNextOutputFile(FileDescriptor fd) throws IllegalStateException, IOException;
871    private native void _prepare() throws IllegalStateException, IOException;
872
873    /**
874     * Prepares the recorder to begin capturing and encoding data. This method
875     * must be called after setting up the desired audio and video sources,
876     * encoders, file format, etc., but before start().
877     *
878     * @throws IllegalStateException if it is called after
879     * start() or before setOutputFormat().
880     * @throws IOException if prepare fails otherwise.
881     */
882    public void prepare() throws IllegalStateException, IOException
883    {
884        if (mPath != null) {
885            RandomAccessFile file = new RandomAccessFile(mPath, "rws");
886            try {
887                _setOutputFile(file.getFD());
888            } finally {
889                file.close();
890            }
891        } else if (mFd != null) {
892            _setOutputFile(mFd);
893        } else {
894            throw new IOException("No valid output file");
895        }
896
897        _prepare();
898    }
899
900    /**
901     * Begins capturing and encoding data to the file specified with
902     * setOutputFile(). Call this after prepare().
903     *
904     * <p>Since API level 13, if applications set a camera via
905     * {@link #setCamera(Camera)}, the apps can use the camera after this method
906     * call. The apps do not need to lock the camera again. However, if this
907     * method fails, the apps should still lock the camera back. The apps should
908     * not start another recording session during recording.
909     *
910     * @throws IllegalStateException if it is called before
911     * prepare().
912     */
913    public native void start() throws IllegalStateException;
914
915    /**
916     * Stops recording. Call this after start(). Once recording is stopped,
917     * you will have to configure it again as if it has just been constructed.
918     * Note that a RuntimeException is intentionally thrown to the
919     * application, if no valid audio/video data has been received when stop()
920     * is called. This happens if stop() is called immediately after
921     * start(). The failure lets the application take action accordingly to
922     * clean up the output file (delete the output file, for instance), since
923     * the output file is not properly constructed when this happens.
924     *
925     * @throws IllegalStateException if it is called before start()
926     */
927    public native void stop() throws IllegalStateException;
928
929    /**
930     * Pauses recording. Call this after start(). You may resume recording
931     * with resume() without reconfiguration, as opposed to stop(). It does
932     * nothing if the recording is already paused.
933     *
934     * When the recording is paused and resumed, the resulting output would
935     * be as if nothing happend during paused period, immediately switching
936     * to the resumed scene.
937     *
938     * @throws IllegalStateException if it is called before start() or after
939     * stop()
940     */
941    public native void pause() throws IllegalStateException;
942
943    /**
944     * Resumes recording. Call this after start(). It does nothing if the
945     * recording is not paused.
946     *
947     * @throws IllegalStateException if it is called before start() or after
948     * stop()
949     * @see android.media.MediaRecorder#pause
950     */
951    public native void resume() throws IllegalStateException;
952
953    /**
954     * Restarts the MediaRecorder to its idle state. After calling
955     * this method, you will have to configure it again as if it had just been
956     * constructed.
957     */
958    public void reset() {
959        native_reset();
960
961        // make sure none of the listeners get called anymore
962        mEventHandler.removeCallbacksAndMessages(null);
963    }
964
965    private native void native_reset();
966
967    /**
968     * Returns the maximum absolute amplitude that was sampled since the last
969     * call to this method. Call this only after the setAudioSource().
970     *
971     * @return the maximum absolute amplitude measured since the last call, or
972     * 0 when called for the first time
973     * @throws IllegalStateException if it is called before
974     * the audio source has been set.
975     */
976    public native int getMaxAmplitude() throws IllegalStateException;
977
978    /* Do not change this value without updating its counterpart
979     * in include/media/mediarecorder.h or mediaplayer.h!
980     */
981    /** Unspecified media recorder error.
982     * @see android.media.MediaRecorder.OnErrorListener
983     */
984    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
985    /** Media server died. In this case, the application must release the
986     * MediaRecorder object and instantiate a new one.
987     * @see android.media.MediaRecorder.OnErrorListener
988     */
989    public static final int MEDIA_ERROR_SERVER_DIED = 100;
990
991    /**
992     * Interface definition for a callback to be invoked when an error
993     * occurs while recording.
994     */
995    public interface OnErrorListener
996    {
997        /**
998         * Called when an error occurs while recording.
999         *
1000         * @param mr the MediaRecorder that encountered the error
1001         * @param what    the type of error that has occurred:
1002         * <ul>
1003         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
1004         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1005         * </ul>
1006         * @param extra   an extra code, specific to the error type
1007         */
1008        void onError(MediaRecorder mr, int what, int extra);
1009    }
1010
1011    /**
1012     * Register a callback to be invoked when an error occurs while
1013     * recording.
1014     *
1015     * @param l the callback that will be run
1016     */
1017    public void setOnErrorListener(OnErrorListener l)
1018    {
1019        mOnErrorListener = l;
1020    }
1021
1022    /* Do not change these values without updating their counterparts
1023     * in include/media/mediarecorder.h!
1024     */
1025    /** Unspecified media recorder info.
1026     * @see android.media.MediaRecorder.OnInfoListener
1027     */
1028    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
1029    /** A maximum duration had been setup and has now been reached.
1030     * @see android.media.MediaRecorder.OnInfoListener
1031     */
1032    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
1033    /** A maximum filesize had been setup and has now been reached.
1034     * Note: This event will not be sent if application already set
1035     * next output file through {@link #setNextOutputFile}.
1036     * @see android.media.MediaRecorder.OnInfoListener
1037     */
1038    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
1039    /** A maximum filesize had been setup and current recorded file size
1040     * has reached 90% of the limit. This is sent once per file upon
1041     * reaching/passing the 90% limit. To continue the recording, applicaiton
1042     * should use {@link #setNextOutputFile} to set the next output file.
1043     * Otherwise, recording will stop when reaching maximum file size.
1044     * @see android.media.MediaRecorder.OnInfoListener
1045     */
1046    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING = 802;
1047    /** A maximum filesize had been reached and MediaRecorder has switched
1048     * output to a new file set by application {@link #setNextOutputFile}.
1049     * For best practice, application should use this event to keep track
1050     * of whether the file previously set has been used or not.
1051     * @see android.media.MediaRecorder.OnInfoListener
1052     */
1053    public static final int MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED = 803;
1054
1055    /** informational events for individual tracks, for testing purpose.
1056     * The track informational event usually contains two parts in the ext1
1057     * arg of the onInfo() callback: bit 31-28 contains the track id; and
1058     * the rest of the 28 bits contains the informational event defined here.
1059     * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
1060     * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
1061     * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
1062     * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
1063     * application should extract the track id and the type of informational
1064     * event from ext1, accordingly.
1065     *
1066     * FIXME:
1067     * Please update the comment for onInfo also when these
1068     * events are unhidden so that application knows how to extract the track
1069     * id and the informational event type from onInfo callback.
1070     *
1071     * {@hide}
1072     */
1073    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
1074    /** Signal the completion of the track for the recording session.
1075     * {@hide}
1076     */
1077    public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
1078    /** Indicate the recording progress in time (ms) during recording.
1079     * {@hide}
1080     */
1081    public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
1082    /** Indicate the track type: 0 for Audio and 1 for Video.
1083     * {@hide}
1084     */
1085    public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
1086    /** Provide the track duration information.
1087     * {@hide}
1088     */
1089    public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
1090    /** Provide the max chunk duration in time (ms) for the given track.
1091     * {@hide}
1092     */
1093    public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
1094    /** Provide the total number of recordd frames.
1095     * {@hide}
1096     */
1097    public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
1098    /** Provide the max spacing between neighboring chunks for the given track.
1099     * {@hide}
1100     */
1101    public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
1102    /** Provide the elapsed time measuring from the start of the recording
1103     * till the first output frame of the given track is received, excluding
1104     * any intentional start time offset of a recording session for the
1105     * purpose of eliminating the recording sound in the recorded file.
1106     * {@hide}
1107     */
1108    public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
1109    /** Provide the start time difference (delay) betweeen this track and
1110     * the start of the movie.
1111     * {@hide}
1112     */
1113    public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
1114    /** Provide the total number of data (in kilo-bytes) encoded.
1115     * {@hide}
1116     */
1117    public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
1118    /**
1119     * {@hide}
1120     */
1121    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
1122
1123
1124    /**
1125     * Interface definition of a callback to be invoked to communicate some
1126     * info and/or warning about the recording.
1127     */
1128    public interface OnInfoListener
1129    {
1130        /**
1131         * Called to indicate an info or a warning during recording.
1132         *
1133         * @param mr   the MediaRecorder the info pertains to
1134         * @param what the type of info or warning that has occurred
1135         * <ul>
1136         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
1137         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
1138         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
1139         * </ul>
1140         * @param extra   an extra code, specific to the info type
1141         */
1142        void onInfo(MediaRecorder mr, int what, int extra);
1143    }
1144
1145    /**
1146     * Register a callback to be invoked when an informational event occurs while
1147     * recording.
1148     *
1149     * @param listener the callback that will be run
1150     */
1151    public void setOnInfoListener(OnInfoListener listener)
1152    {
1153        mOnInfoListener = listener;
1154    }
1155
1156    private class EventHandler extends Handler
1157    {
1158        private MediaRecorder mMediaRecorder;
1159
1160        public EventHandler(MediaRecorder mr, Looper looper) {
1161            super(looper);
1162            mMediaRecorder = mr;
1163        }
1164
1165        /* Do not change these values without updating their counterparts
1166         * in include/media/mediarecorder.h!
1167         */
1168        private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
1169        private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
1170        private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
1171        private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
1172
1173        /* Events related to individual tracks */
1174        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
1175        private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
1176        private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
1177        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
1178
1179
1180        @Override
1181        public void handleMessage(Message msg) {
1182            if (mMediaRecorder.mNativeContext == 0) {
1183                Log.w(TAG, "mediarecorder went away with unhandled events");
1184                return;
1185            }
1186            switch(msg.what) {
1187            case MEDIA_RECORDER_EVENT_ERROR:
1188            case MEDIA_RECORDER_TRACK_EVENT_ERROR:
1189                if (mOnErrorListener != null)
1190                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
1191
1192                return;
1193
1194            case MEDIA_RECORDER_EVENT_INFO:
1195            case MEDIA_RECORDER_TRACK_EVENT_INFO:
1196                if (mOnInfoListener != null)
1197                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
1198
1199                return;
1200
1201            default:
1202                Log.e(TAG, "Unknown message type " + msg.what);
1203                return;
1204            }
1205        }
1206    }
1207
1208    /**
1209     * Called from native code when an interesting event happens.  This method
1210     * just uses the EventHandler system to post the event back to the main app thread.
1211     * We use a weak reference to the original MediaRecorder object so that the native
1212     * code is safe from the object disappearing from underneath it.  (This is
1213     * the cookie passed to native_setup().)
1214     */
1215    private static void postEventFromNative(Object mediarecorder_ref,
1216                                            int what, int arg1, int arg2, Object obj)
1217    {
1218        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
1219        if (mr == null) {
1220            return;
1221        }
1222
1223        if (mr.mEventHandler != null) {
1224            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1225            mr.mEventHandler.sendMessage(m);
1226        }
1227    }
1228
1229    /**
1230     * Releases resources associated with this MediaRecorder object.
1231     * It is good practice to call this method when you're done
1232     * using the MediaRecorder. In particular, whenever an Activity
1233     * of an application is paused (its onPause() method is called),
1234     * or stopped (its onStop() method is called), this method should be
1235     * invoked to release the MediaRecorder object, unless the application
1236     * has a special need to keep the object around. In addition to
1237     * unnecessary resources (such as memory and instances of codecs)
1238     * being held, failure to call this method immediately if a
1239     * MediaRecorder object is no longer needed may also lead to
1240     * continuous battery consumption for mobile devices, and recording
1241     * failure for other applications if no multiple instances of the
1242     * same codec are supported on a device. Even if multiple instances
1243     * of the same codec are supported, some performance degradation
1244     * may be expected when unnecessary multiple instances are used
1245     * at the same time.
1246     */
1247    public native void release();
1248
1249    private static native final void native_init();
1250
1251    private native final void native_setup(Object mediarecorder_this,
1252            String clientName, String opPackageName) throws IllegalStateException;
1253
1254    private native final void native_finalize();
1255
1256    private native void setParameter(String nameValuePair);
1257
1258    @Override
1259    protected void finalize() { native_finalize(); }
1260}
1261