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