• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.CallbackExecutor;
20 import android.annotation.FloatRange;
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.RequiresPermission;
25 import android.annotation.SystemApi;
26 import android.app.ActivityThread;
27 import android.compat.annotation.UnsupportedAppUsage;
28 import android.content.AttributionSource;
29 import android.content.AttributionSource.ScopedParcelState;
30 import android.content.Context;
31 import android.hardware.Camera;
32 import android.media.metrics.LogSessionId;
33 import android.os.Build;
34 import android.os.Handler;
35 import android.os.Looper;
36 import android.os.Message;
37 import android.os.Parcel;
38 import android.os.PersistableBundle;
39 import android.util.ArrayMap;
40 import android.util.Log;
41 import android.util.Pair;
42 import android.view.Surface;
43 
44 import com.android.internal.annotations.GuardedBy;
45 import com.android.internal.util.Preconditions;
46 
47 import java.io.File;
48 import java.io.FileDescriptor;
49 import java.io.IOException;
50 import java.io.RandomAccessFile;
51 import java.lang.annotation.Retention;
52 import java.lang.annotation.RetentionPolicy;
53 import java.lang.ref.WeakReference;
54 import java.util.ArrayList;
55 import java.util.List;
56 import java.util.Objects;
57 import java.util.concurrent.Executor;
58 
59 /**
60  * Used to record audio and video. The recording control is based on a
61  * simple state machine (see below).
62  *
63  * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" />
64  * </p>
65  *
66  * <p>A common case of using MediaRecorder to record audio works as follows:
67  *
68  * <pre>MediaRecorder recorder = new MediaRecorder();
69  * recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
70  * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
71  * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
72  * recorder.setOutputFile(PATH_NAME);
73  * recorder.prepare();
74  * recorder.start();   // Recording is now started
75  * ...
76  * recorder.stop();
77  * recorder.reset();   // You can reuse the object by going back to setAudioSource() step
78  * recorder.release(); // Now the object cannot be reused
79  * </pre>
80  *
81  * <p>Applications may want to register for informational and error
82  * events in order to be informed of some internal update and possible
83  * runtime errors during recording. Registration for such events is
84  * done by setting the appropriate listeners (via calls
85  * (to {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener and/or
86  * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener).
87  * In order to receive the respective callback associated with these listeners,
88  * applications are required to create MediaRecorder objects on threads with a
89  * Looper running (the main UI thread by default already has a Looper running).
90  *
91  * <p><strong>Note:</strong> Currently, MediaRecorder does not work on the emulator.
92  *
93  * <div class="special reference">
94  * <h3>Developer Guides</h3>
95  * <p>For more information about how to use MediaRecorder for recording video, read the
96  * <a href="{@docRoot}guide/topics/media/camera.html#capture-video">Camera</a> developer guide.
97  * For more information about how to use MediaRecorder for recording sound, read the
98  * <a href="{@docRoot}guide/topics/media/audio-capture.html">Audio Capture</a> developer guide.</p>
99  * </div>
100  */
101 public class MediaRecorder implements AudioRouting,
102                                       AudioRecordingMonitor,
103                                       AudioRecordingMonitorClient,
104                                       MicrophoneDirection
105 {
106     static {
107         System.loadLibrary("media_jni");
native_init()108         native_init();
109     }
110     private final static String TAG = "MediaRecorder";
111 
112     // The two fields below are accessed by native methods
113     @SuppressWarnings("unused")
114     private long mNativeContext;
115 
116     @SuppressWarnings("unused")
117     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
118     private Surface mSurface;
119 
120     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
121     private String mPath;
122     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
123     private FileDescriptor mFd;
124     private File mFile;
125     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
126     private EventHandler mEventHandler;
127     @UnsupportedAppUsage
128     private OnErrorListener mOnErrorListener;
129     @UnsupportedAppUsage
130     private OnInfoListener mOnInfoListener;
131 
132     private int mChannelCount;
133 
134     @NonNull private LogSessionId mLogSessionId = LogSessionId.LOG_SESSION_ID_NONE;
135 
136     /**
137      * Default constructor.
138      *
139      * @deprecated Use {@link #MediaRecorder(Context)} instead
140      */
141     @Deprecated
MediaRecorder()142     public MediaRecorder() {
143         this(ActivityThread.currentApplication());
144     }
145 
146     /**
147      * Default constructor.
148      *
149      * @param context Context the recorder belongs to
150      */
MediaRecorder(@onNull Context context)151     public MediaRecorder(@NonNull Context context) {
152         Objects.requireNonNull(context);
153         Looper looper;
154         if ((looper = Looper.myLooper()) != null) {
155             mEventHandler = new EventHandler(this, looper);
156         } else if ((looper = Looper.getMainLooper()) != null) {
157             mEventHandler = new EventHandler(this, looper);
158         } else {
159             mEventHandler = null;
160         }
161 
162         mChannelCount = 1;
163         /* Native setup requires a weak reference to our object.
164          * It's easier to create it here than in C++.
165          */
166         try (ScopedParcelState attributionSourceState = context.getAttributionSource()
167                 .asScopedParcelState()) {
168             native_setup(new WeakReference<>(this), ActivityThread.currentPackageName(),
169                     attributionSourceState.getParcel());
170         }
171     }
172 
173     /**
174      * Sets the {@link LogSessionId} for MediaRecorder.
175      *
176      * @param id the global ID for monitoring the MediaRecorder performance
177      */
setLogSessionId(@onNull LogSessionId id)178     public void setLogSessionId(@NonNull LogSessionId id) {
179         Objects.requireNonNull(id);
180         mLogSessionId = id;
181         setParameter("log-session-id=" + id.getStringId());
182     }
183 
184     /**
185      * Returns the {@link LogSessionId} for MediaRecorder.
186      *
187      * @return the global ID for monitoring the MediaRecorder performance
188      */
189     @NonNull
getLogSessionId()190     public LogSessionId getLogSessionId() {
191         return mLogSessionId;
192     }
193 
194     /**
195      * Sets a {@link android.hardware.Camera} to use for recording.
196      *
197      * <p>Use this function to switch quickly between preview and capture mode without a teardown of
198      * the camera object. {@link android.hardware.Camera#unlock()} should be called before
199      * this. Must call before {@link #prepare}.</p>
200      *
201      * @param c the Camera to use for recording
202      * @deprecated Use {@link #getSurface} and the {@link android.hardware.camera2} API instead.
203      */
204     @Deprecated
setCamera(Camera c)205     public native void setCamera(Camera c);
206 
207     /**
208      * Gets the surface to record from when using SURFACE video source.
209      *
210      * <p> May only be called after {@link #prepare}. Frames rendered to the Surface before
211      * {@link #start} will be discarded.</p>
212      *
213      * @throws IllegalStateException if it is called before {@link #prepare}, after
214      * {@link #stop}, or is called when VideoSource is not set to SURFACE.
215      * @see android.media.MediaRecorder.VideoSource
216      */
getSurface()217     public native Surface getSurface();
218 
219     /**
220      * Configures the recorder to use a persistent surface when using SURFACE video source.
221      * <p> May only be called before {@link #prepare}. If called, {@link #getSurface} should
222      * not be used and will throw IllegalStateException. Frames rendered to the Surface
223      * before {@link #start} will be discarded.</p>
224 
225      * @param surface a persistent input surface created by
226      *           {@link MediaCodec#createPersistentInputSurface}
227      * @throws IllegalStateException if it is called after {@link #prepare} and before
228      * {@link #stop}.
229      * @throws IllegalArgumentException if the surface was not created by
230      *           {@link MediaCodec#createPersistentInputSurface}.
231      * @see MediaCodec#createPersistentInputSurface
232      * @see MediaRecorder.VideoSource
233      */
setInputSurface(@onNull Surface surface)234     public void setInputSurface(@NonNull Surface surface) {
235         if (!(surface instanceof MediaCodec.PersistentSurface)) {
236             throw new IllegalArgumentException("not a PersistentSurface");
237         }
238         native_setInputSurface(surface);
239     }
240 
native_setInputSurface(@onNull Surface surface)241     private native final void native_setInputSurface(@NonNull Surface surface);
242 
243     /**
244      * Sets a Surface to show a preview of recorded media (video). Calls this
245      * before prepare() to make sure that the desirable preview display is
246      * set. If {@link #setCamera(Camera)} is used and the surface has been
247      * already set to the camera, application do not need to call this. If
248      * this is called with non-null surface, the preview surface of the camera
249      * will be replaced by the new surface. If this method is called with null
250      * surface or not called at all, media recorder will not change the preview
251      * surface of the camera.
252      *
253      * @param sv the Surface to use for the preview
254      * @see android.hardware.Camera#setPreviewDisplay(android.view.SurfaceHolder)
255      */
setPreviewDisplay(Surface sv)256     public void setPreviewDisplay(Surface sv) {
257         mSurface = sv;
258     }
259 
260     /**
261      * Defines the audio source.
262      * An audio source defines both a default physical source of audio signal, and a recording
263      * configuration. These constants are for instance used
264      * in {@link MediaRecorder#setAudioSource(int)} or
265      * {@link AudioRecord.Builder#setAudioSource(int)}.
266      */
267     public final class AudioSource {
268 
AudioSource()269         private AudioSource() {}
270 
271         /** @hide */
272         public final static int AUDIO_SOURCE_INVALID = -1;
273 
274       /* Do not change these values without updating their counterparts
275        * in system/media/audio/include/system/audio.h!
276        */
277 
278         /** Default audio source **/
279         public static final int DEFAULT = 0;
280 
281         /** Microphone audio source */
282         public static final int MIC = 1;
283 
284         /** Voice call uplink (Tx) audio source.
285          * <p>
286          * Capturing from <code>VOICE_UPLINK</code> source requires the
287          * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
288          * This permission is reserved for use by system components and is not available to
289          * third-party applications.
290          * </p>
291          */
292         public static final int VOICE_UPLINK = 2;
293 
294         /** Voice call downlink (Rx) audio source.
295          * <p>
296          * Capturing from <code>VOICE_DOWNLINK</code> source requires the
297          * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
298          * This permission is reserved for use by system components and is not available to
299          * third-party applications.
300          * </p>
301          */
302         public static final int VOICE_DOWNLINK = 3;
303 
304         /** Voice call uplink + downlink audio source
305          * <p>
306          * Capturing from <code>VOICE_CALL</code> source requires the
307          * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
308          * This permission is reserved for use by system components and is not available to
309          * third-party applications.
310          * </p>
311          */
312         public static final int VOICE_CALL = 4;
313 
314         /** Microphone audio source tuned for video recording, with the same orientation
315          *  as the camera if available. */
316         public static final int CAMCORDER = 5;
317 
318         /** Microphone audio source tuned for voice recognition. */
319         public static final int VOICE_RECOGNITION = 6;
320 
321         /** Microphone audio source tuned for voice communications such as VoIP. It
322          *  will for instance take advantage of echo cancellation or automatic gain control
323          *  if available.
324          */
325         public static final int VOICE_COMMUNICATION = 7;
326 
327         /**
328          * Audio source for a submix of audio streams to be presented remotely.
329          * <p>
330          * An application can use this audio source to capture a mix of audio streams
331          * that should be transmitted to a remote receiver such as a Wifi display.
332          * While recording is active, these audio streams are redirected to the remote
333          * submix instead of being played on the device speaker or headset.
334          * </p><p>
335          * Certain streams are excluded from the remote submix, including
336          * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_ALARM},
337          * and {@link AudioManager#STREAM_NOTIFICATION}.  These streams will continue
338          * to be presented locally as usual.
339          * </p><p>
340          * Capturing the remote submix audio requires the
341          * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
342          * This permission is reserved for use by system components and is not available to
343          * third-party applications.
344          * </p>
345          */
346         @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_OUTPUT)
347         public static final int REMOTE_SUBMIX = 8;
348 
349         /** Microphone audio source tuned for unprocessed (raw) sound if available, behaves like
350          *  {@link #DEFAULT} otherwise. */
351         public static final int UNPROCESSED = 9;
352 
353 
354         /**
355          * Source for capturing audio meant to be processed in real time and played back for live
356          * performance (e.g karaoke).
357          * <p>
358          * The capture path will minimize latency and coupling with
359          * playback path.
360          * </p>
361          */
362         public static final int VOICE_PERFORMANCE = 10;
363 
364         /**
365          * Source for an echo canceller to capture the reference signal to be cancelled.
366          * <p>
367          * The echo reference signal will be captured as close as possible to the DAC in order
368          * to include all post processing applied to the playback path.
369          * </p><p>
370          * Capturing the echo reference requires the
371          * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
372          * This permission is reserved for use by system components and is not available to
373          * third-party applications.
374          * </p>
375          * @hide
376          */
377         @SystemApi
378         @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_OUTPUT)
379         public static final int ECHO_REFERENCE = 1997;
380 
381         /**
382          * Audio source for capturing broadcast radio tuner output.
383          * Capturing the radio tuner output requires the
384          * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
385          * This permission is reserved for use by system components and is not available to
386          * third-party applications.
387          * @hide
388          */
389         @SystemApi
390         @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_OUTPUT)
391         public static final int RADIO_TUNER = 1998;
392 
393         /**
394          * Audio source for preemptible, low-priority software hotword detection
395          * It presents the same gain and pre-processing tuning as {@link #VOICE_RECOGNITION}.
396          * <p>
397          * An application should use this audio source when it wishes to do
398          * always-on software hotword detection, while gracefully giving in to any other application
399          * that might want to read from the microphone.
400          * </p>
401          * This is a hidden audio source.
402          * @hide
403          */
404         @SystemApi
405         @RequiresPermission(android.Manifest.permission.CAPTURE_AUDIO_HOTWORD)
406         public static final int HOTWORD = 1999;
407     }
408 
409     /** @hide */
410     @IntDef({
411         AudioSource.DEFAULT,
412         AudioSource.MIC,
413         AudioSource.VOICE_UPLINK,
414         AudioSource.VOICE_DOWNLINK,
415         AudioSource.VOICE_CALL,
416         AudioSource.CAMCORDER,
417         AudioSource.VOICE_RECOGNITION,
418         AudioSource.VOICE_COMMUNICATION,
419         AudioSource.UNPROCESSED,
420         AudioSource.VOICE_PERFORMANCE,
421     })
422     @Retention(RetentionPolicy.SOURCE)
423     public @interface Source {}
424 
425     /** @hide */
426     @IntDef({
427         AudioSource.DEFAULT,
428         AudioSource.MIC,
429         AudioSource.VOICE_UPLINK,
430         AudioSource.VOICE_DOWNLINK,
431         AudioSource.VOICE_CALL,
432         AudioSource.CAMCORDER,
433         AudioSource.VOICE_RECOGNITION,
434         AudioSource.VOICE_COMMUNICATION,
435         AudioSource.REMOTE_SUBMIX,
436         AudioSource.UNPROCESSED,
437         AudioSource.VOICE_PERFORMANCE,
438         AudioSource.ECHO_REFERENCE,
439         AudioSource.RADIO_TUNER,
440         AudioSource.HOTWORD,
441     })
442     @Retention(RetentionPolicy.SOURCE)
443     public @interface SystemSource {}
444 
445     // TODO make AudioSource static (API change) and move this method inside the AudioSource class
446     /**
447      * @hide
448      * @param source An audio source to test
449      * @return true if the source is only visible to system components
450      */
isSystemOnlyAudioSource(int source)451     public static boolean isSystemOnlyAudioSource(int source) {
452         switch(source) {
453         case AudioSource.DEFAULT:
454         case AudioSource.MIC:
455         case AudioSource.VOICE_UPLINK:
456         case AudioSource.VOICE_DOWNLINK:
457         case AudioSource.VOICE_CALL:
458         case AudioSource.CAMCORDER:
459         case AudioSource.VOICE_RECOGNITION:
460         case AudioSource.VOICE_COMMUNICATION:
461         //case REMOTE_SUBMIX:  considered "system" as it requires system permissions
462         case AudioSource.UNPROCESSED:
463         case AudioSource.VOICE_PERFORMANCE:
464             return false;
465         default:
466             return true;
467         }
468     }
469 
470     /**
471      * @hide
472      * @param source An audio source to test
473      * @return true if the source is a valid one
474      */
isValidAudioSource(int source)475     public static boolean isValidAudioSource(int source) {
476         switch(source) {
477             case AudioSource.MIC:
478             case AudioSource.VOICE_UPLINK:
479             case AudioSource.VOICE_DOWNLINK:
480             case AudioSource.VOICE_CALL:
481             case AudioSource.CAMCORDER:
482             case AudioSource.VOICE_RECOGNITION:
483             case AudioSource.VOICE_COMMUNICATION:
484             case AudioSource.REMOTE_SUBMIX:
485             case AudioSource.UNPROCESSED:
486             case AudioSource.VOICE_PERFORMANCE:
487             case AudioSource.ECHO_REFERENCE:
488             case AudioSource.RADIO_TUNER:
489             case AudioSource.HOTWORD:
490                 return true;
491             default:
492                 return false;
493         }
494     }
495 
496     /** @hide */
toLogFriendlyAudioSource(int source)497     public static final String toLogFriendlyAudioSource(int source) {
498         switch(source) {
499         case AudioSource.DEFAULT:
500             return "DEFAULT";
501         case AudioSource.MIC:
502             return "MIC";
503         case AudioSource.VOICE_UPLINK:
504             return "VOICE_UPLINK";
505         case AudioSource.VOICE_DOWNLINK:
506             return "VOICE_DOWNLINK";
507         case AudioSource.VOICE_CALL:
508             return "VOICE_CALL";
509         case AudioSource.CAMCORDER:
510             return "CAMCORDER";
511         case AudioSource.VOICE_RECOGNITION:
512             return "VOICE_RECOGNITION";
513         case AudioSource.VOICE_COMMUNICATION:
514             return "VOICE_COMMUNICATION";
515         case AudioSource.REMOTE_SUBMIX:
516             return "REMOTE_SUBMIX";
517         case AudioSource.UNPROCESSED:
518             return "UNPROCESSED";
519         case AudioSource.ECHO_REFERENCE:
520             return "ECHO_REFERENCE";
521         case AudioSource.VOICE_PERFORMANCE:
522             return "VOICE_PERFORMANCE";
523         case AudioSource.RADIO_TUNER:
524             return "RADIO_TUNER";
525         case AudioSource.HOTWORD:
526             return "HOTWORD";
527         case AudioSource.AUDIO_SOURCE_INVALID:
528             return "AUDIO_SOURCE_INVALID";
529         default:
530             return "unknown source " + source;
531         }
532     }
533 
534     /**
535      * Defines the video source. These constants are used with
536      * {@link MediaRecorder#setVideoSource(int)}.
537      */
538     public final class VideoSource {
539       /* Do not change these values without updating their counterparts
540        * in include/media/mediarecorder.h!
541        */
VideoSource()542         private VideoSource() {}
543         public static final int DEFAULT = 0;
544         /** Camera video source
545          * <p>
546          * Using the {@link android.hardware.Camera} API as video source.
547          * </p>
548          */
549         public static final int CAMERA = 1;
550         /** Surface video source
551          * <p>
552          * Using a Surface as video source.
553          * </p><p>
554          * This flag must be used when recording from an
555          * {@link android.hardware.camera2} API source.
556          * </p><p>
557          * When using this video source type, use {@link MediaRecorder#getSurface()}
558          * to retrieve the surface created by MediaRecorder.
559          */
560         public static final int SURFACE = 2;
561     }
562 
563     /**
564      * Defines the output format. These constants are used with
565      * {@link MediaRecorder#setOutputFormat(int)}.
566      */
567     public final class OutputFormat {
568       /* Do not change these values without updating their counterparts
569        * in include/media/mediarecorder.h!
570        */
OutputFormat()571         private OutputFormat() {}
572         public static final int DEFAULT = 0;
573         /** 3GPP media file format*/
574         public static final int THREE_GPP = 1;
575         /** MPEG4 media file format*/
576         public static final int MPEG_4 = 2;
577 
578         /** The following formats are audio only .aac or .amr formats */
579 
580         /**
581          * AMR NB file format
582          * @deprecated  Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
583          */
584         public static final int RAW_AMR = 3;
585 
586         /** AMR NB file format */
587         public static final int AMR_NB = 3;
588 
589         /** AMR WB file format */
590         public static final int AMR_WB = 4;
591 
592         /** @hide AAC ADIF file format */
593         public static final int AAC_ADIF = 5;
594 
595         /** AAC ADTS file format */
596         public static final int AAC_ADTS = 6;
597 
598         /** @hide Stream over a socket, limited to a single stream */
599         public static final int OUTPUT_FORMAT_RTP_AVP = 7;
600 
601         /** H.264/AAC data encapsulated in MPEG2/TS */
602         public static final int MPEG_2_TS = 8;
603 
604         /** VP8/VORBIS data in a WEBM container */
605         public static final int WEBM = 9;
606 
607         /** @hide HEIC data in a HEIF container */
608         public static final int HEIF = 10;
609 
610         /** Opus data in a Ogg container */
611         public static final int OGG = 11;
612     };
613 
614     /**
615      * @hide
616      */
617     @IntDef({
618         OutputFormat.DEFAULT,
619         OutputFormat.THREE_GPP,
620         OutputFormat.MPEG_4,
621         OutputFormat.AMR_NB,
622         OutputFormat.AMR_WB,
623         OutputFormat.AAC_ADIF,
624         OutputFormat.AAC_ADTS,
625         OutputFormat.MPEG_2_TS,
626         OutputFormat.WEBM,
627         OutputFormat.HEIF,
628         OutputFormat.OGG,
629     })
630     @Retention(RetentionPolicy.SOURCE)
631     public @interface OutputFormatValues {}
632 
633     /**
634      * Defines the audio encoding. These constants are used with
635      * {@link MediaRecorder#setAudioEncoder(int)}.
636      */
637     public final class AudioEncoder {
638       /* Do not change these values without updating their counterparts
639        * in include/media/mediarecorder.h!
640        */
AudioEncoder()641         private AudioEncoder() {}
642         public static final int DEFAULT = 0;
643         /** AMR (Narrowband) audio codec */
644         public static final int AMR_NB = 1;
645         /** AMR (Wideband) audio codec */
646         public static final int AMR_WB = 2;
647         /** AAC Low Complexity (AAC-LC) audio codec */
648         public static final int AAC = 3;
649         /** High Efficiency AAC (HE-AAC) audio codec */
650         public static final int HE_AAC = 4;
651         /** Enhanced Low Delay AAC (AAC-ELD) audio codec */
652         public static final int AAC_ELD = 5;
653         /** Ogg Vorbis audio codec (Support is optional) */
654         public static final int VORBIS = 6;
655         /** Opus audio codec */
656         public static final int OPUS = 7;
657     }
658 
659     /**
660      * @hide
661      */
662     @IntDef({
663         AudioEncoder.DEFAULT,
664         AudioEncoder.AMR_NB,
665         AudioEncoder.AMR_WB,
666         AudioEncoder.AAC,
667         AudioEncoder.HE_AAC,
668         AudioEncoder.AAC_ELD,
669         AudioEncoder.VORBIS,
670         AudioEncoder.OPUS,
671     })
672     @Retention(RetentionPolicy.SOURCE)
673     public @interface AudioEncoderValues {}
674 
675     /**
676      * Defines the video encoding. These constants are used with
677      * {@link MediaRecorder#setVideoEncoder(int)}.
678      */
679     public final class VideoEncoder {
680       /* Do not change these values without updating their counterparts
681        * in include/media/mediarecorder.h!
682        */
VideoEncoder()683         private VideoEncoder() {}
684         public static final int DEFAULT = 0;
685         public static final int H263 = 1;
686         public static final int H264 = 2;
687         public static final int MPEG_4_SP = 3;
688         public static final int VP8 = 4;
689         public static final int HEVC = 5;
690     }
691 
692     /**
693      * @hide
694      */
695     @IntDef({
696         VideoEncoder.DEFAULT,
697         VideoEncoder.H263,
698         VideoEncoder.H264,
699         VideoEncoder.MPEG_4_SP,
700         VideoEncoder.VP8,
701         VideoEncoder.HEVC,
702     })
703     @Retention(RetentionPolicy.SOURCE)
704     public @interface VideoEncoderValues {}
705 
706     /**
707      * Sets the audio source to be used for recording. If this method is not
708      * called, the output file will not contain an audio track. The source needs
709      * to be specified before setting recording-parameters or encoders. Call
710      * this only before setOutputFormat().
711      *
712      * @param audioSource the audio source to use
713      * @throws IllegalStateException if it is called after setOutputFormat()
714      * @see android.media.MediaRecorder.AudioSource
715      */
setAudioSource(@ource int audioSource)716     public native void setAudioSource(@Source int audioSource)
717             throws IllegalStateException;
718 
719     /**
720      * Gets the maximum value for audio sources.
721      * @see android.media.MediaRecorder.AudioSource
722      */
getAudioSourceMax()723     public static final int getAudioSourceMax() {
724         return AudioSource.VOICE_PERFORMANCE;
725     }
726 
727     /**
728      * Indicates that this capture request is privacy sensitive and that
729      * any concurrent capture is not permitted.
730      * <p>
731      * The default is not privacy sensitive except when the audio source set with
732      * {@link #setAudioSource(int)} is {@link AudioSource#VOICE_COMMUNICATION} or
733      * {@link AudioSource#CAMCORDER}.
734      * <p>
735      * Always takes precedence over default from audio source when set explicitly.
736      * <p>
737      * Using this API is only permitted when the audio source is one of:
738      * <ul>
739      * <li>{@link AudioSource#MIC}</li>
740      * <li>{@link AudioSource#CAMCORDER}</li>
741      * <li>{@link AudioSource#VOICE_RECOGNITION}</li>
742      * <li>{@link AudioSource#VOICE_COMMUNICATION}</li>
743      * <li>{@link AudioSource#UNPROCESSED}</li>
744      * <li>{@link AudioSource#VOICE_PERFORMANCE}</li>
745      * </ul>
746      * Invoking {@link #prepare()} will throw an IOException if this
747      * condition is not met.
748      * <p>
749      * Must be called after {@link #setAudioSource(int)} and before {@link #setOutputFormat(int)}.
750      * @param privacySensitive True if capture from this MediaRecorder must be marked as privacy
751      * sensitive, false otherwise.
752      * @throws IllegalStateException if called before {@link #setAudioSource(int)}
753      * or after {@link #setOutputFormat(int)}
754      */
setPrivacySensitive(boolean privacySensitive)755     public native void setPrivacySensitive(boolean privacySensitive);
756 
757     /**
758      * Returns whether this MediaRecorder is marked as privacy sensitive or not with
759      * regard to audio capture.
760      * <p>
761      * See {@link #setPrivacySensitive(boolean)}
762      * <p>
763      * @return true if privacy sensitive, false otherwise
764      */
isPrivacySensitive()765     public native boolean isPrivacySensitive();
766 
767     /**
768      * Sets the video source to be used for recording. If this method is not
769      * called, the output file will not contain an video track. The source needs
770      * to be specified before setting recording-parameters or encoders. Call
771      * this only before setOutputFormat().
772      *
773      * @param video_source the video source to use
774      * @throws IllegalStateException if it is called after setOutputFormat()
775      * @see android.media.MediaRecorder.VideoSource
776      */
setVideoSource(int video_source)777     public native void setVideoSource(int video_source)
778             throws IllegalStateException;
779 
780     /**
781      * Uses the settings from a CamcorderProfile object for recording. This method should
782      * be called after the video AND audio sources are set, and before setOutputFile().
783      * If a time lapse CamcorderProfile is used, audio related source or recording
784      * parameters are ignored.
785      *
786      * @param profile the CamcorderProfile to use
787      * @see android.media.CamcorderProfile
788      */
setProfile(CamcorderProfile profile)789     public void setProfile(CamcorderProfile profile) {
790         setOutputFormat(profile.fileFormat);
791         setVideoFrameRate(profile.videoFrameRate);
792         setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
793         setVideoEncodingBitRate(profile.videoBitRate);
794         setVideoEncoder(profile.videoCodec);
795         if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW &&
796              profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) {
797             // Nothing needs to be done. Call to setCaptureRate() enables
798             // time lapse video recording.
799         } else {
800             setAudioEncodingBitRate(profile.audioBitRate);
801             setAudioChannels(profile.audioChannels);
802             setAudioSamplingRate(profile.audioSampleRate);
803             setAudioEncoder(profile.audioCodec);
804         }
805     }
806 
807     /**
808      * Uses the settings from an AudioProfile for recording.
809      * <p>
810      * This method should be called after the video AND audio sources are set, and before
811      * setOutputFile().
812      * <p>
813      * This method can be used instead of {@link #setProfile} when using EncoderProfiles.
814      *
815      * @param profile the AudioProfile to use
816      * @see android.media.EncoderProfiles
817      * @see android.media.CamcorderProfile#getAll
818      */
setAudioProfile(@onNull EncoderProfiles.AudioProfile profile)819     public void setAudioProfile(@NonNull EncoderProfiles.AudioProfile profile) {
820         setAudioEncodingBitRate(profile.getBitrate());
821         setAudioChannels(profile.getChannels());
822         setAudioSamplingRate(profile.getSampleRate());
823         setAudioEncoder(profile.getCodec());
824     }
825 
826     /**
827      * Uses the settings from a VideoProfile object for recording.
828      * <p>
829      * This method should be called after the video AND audio sources are set, and before
830      * setOutputFile().
831      * <p>
832      * This method can be used instead of {@link #setProfile} when using EncoderProfiles.
833      *
834      * @param profile the VideoProfile to use
835      * @see android.media.EncoderProfiles
836      * @see android.media.CamcorderProfile#getAll
837      */
setVideoProfile(@onNull EncoderProfiles.VideoProfile profile)838     public void setVideoProfile(@NonNull EncoderProfiles.VideoProfile profile) {
839         setVideoFrameRate(profile.getFrameRate());
840         setVideoSize(profile.getWidth(), profile.getHeight());
841         setVideoEncodingBitRate(profile.getBitrate());
842         setVideoEncoder(profile.getCodec());
843         if (profile.getProfile() >= 0) {
844             setVideoEncodingProfileLevel(profile.getProfile(), 0 /* level */);
845         }
846     }
847 
848     /**
849      * Set video frame capture rate. This can be used to set a different video frame capture
850      * rate than the recorded video's playback rate. This method also sets the recording mode
851      * to time lapse. In time lapse video recording, only video is recorded. Audio related
852      * parameters are ignored when a time lapse recording session starts, if an application
853      * sets them.
854      *
855      * @param fps Rate at which frames should be captured in frames per second.
856      * The fps can go as low as desired. However the fastest fps will be limited by the hardware.
857      * For resolutions that can be captured by the video camera, the fastest fps can be computed using
858      * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher
859      * resolutions the fastest fps may be more restrictive.
860      * Note that the recorder cannot guarantee that frames will be captured at the
861      * given rate due to camera/encoder limitations. However it tries to be as close as
862      * possible.
863      */
setCaptureRate(double fps)864     public void setCaptureRate(double fps) {
865         // Make sure that time lapse is enabled when this method is called.
866         setParameter("time-lapse-enable=1");
867         setParameter("time-lapse-fps=" + fps);
868     }
869 
870     /**
871      * Sets the orientation hint for output video playback.
872      * This method should be called before prepare(). This method will not
873      * trigger the source video frame to rotate during video recording, but to
874      * add a composition matrix containing the rotation angle in the output
875      * video if the output format is OutputFormat.THREE_GPP or
876      * OutputFormat.MPEG_4 so that a video player can choose the proper
877      * orientation for playback. Note that some video players may choose
878      * to ignore the compostion matrix in a video during playback.
879      *
880      * @param degrees the angle to be rotated clockwise in degrees.
881      * The supported angles are 0, 90, 180, and 270 degrees.
882      * @throws IllegalArgumentException if the angle is not supported.
883      *
884      */
setOrientationHint(int degrees)885     public void setOrientationHint(int degrees) {
886         if (degrees != 0   &&
887             degrees != 90  &&
888             degrees != 180 &&
889             degrees != 270) {
890             throw new IllegalArgumentException("Unsupported angle: " + degrees);
891         }
892         setParameter("video-param-rotation-angle-degrees=" + degrees);
893     }
894 
895     /**
896      * Set and store the geodata (latitude and longitude) in the output file.
897      * This method should be called before prepare(). The geodata is
898      * stored in udta box if the output format is OutputFormat.THREE_GPP
899      * or OutputFormat.MPEG_4, and is ignored for other output formats.
900      * The geodata is stored according to ISO-6709 standard.
901      *
902      * @param latitude latitude in degrees. Its value must be in the
903      * range [-90, 90].
904      * @param longitude longitude in degrees. Its value must be in the
905      * range [-180, 180].
906      *
907      * @throws IllegalArgumentException if the given latitude or
908      * longitude is out of range.
909      *
910      */
setLocation(float latitude, float longitude)911     public void setLocation(float latitude, float longitude) {
912         int latitudex10000  = (int) (latitude * 10000 + 0.5);
913         int longitudex10000 = (int) (longitude * 10000 + 0.5);
914 
915         if (latitudex10000 > 900000 || latitudex10000 < -900000) {
916             String msg = "Latitude: " + latitude + " out of range.";
917             throw new IllegalArgumentException(msg);
918         }
919         if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
920             String msg = "Longitude: " + longitude + " out of range";
921             throw new IllegalArgumentException(msg);
922         }
923 
924         setParameter("param-geotag-latitude=" + latitudex10000);
925         setParameter("param-geotag-longitude=" + longitudex10000);
926     }
927 
928     /**
929      * Sets the format of the output file produced during recording. Call this
930      * after setAudioSource()/setVideoSource() but before prepare().
931      *
932      * <p>It is recommended to always use 3GP format when using the H.263
933      * video encoder and AMR audio encoder. Using an MPEG-4 container format
934      * may confuse some desktop players.</p>
935      *
936      * @param output_format the output format to use. The output format
937      * needs to be specified before setting recording-parameters or encoders.
938      * @throws IllegalStateException if it is called after prepare() or before
939      * setAudioSource()/setVideoSource().
940      * @see android.media.MediaRecorder.OutputFormat
941      */
setOutputFormat(@utputFormatValues int output_format)942     public native void setOutputFormat(@OutputFormatValues int output_format)
943             throws IllegalStateException;
944 
945     /**
946      * Sets the width and height of the video to be captured.  Must be called
947      * after setVideoSource(). Call this after setOutputFormat() but before
948      * prepare().
949      *
950      * @param width the width of the video to be captured
951      * @param height the height of the video to be captured
952      * @throws IllegalStateException if it is called after
953      * prepare() or before setOutputFormat()
954      */
setVideoSize(int width, int height)955     public native void setVideoSize(int width, int height)
956             throws IllegalStateException;
957 
958     /**
959      * Sets the frame rate of the video to be captured.  Must be called
960      * after setVideoSource(). Call this after setOutputFormat() but before
961      * prepare().
962      *
963      * @param rate the number of frames per second of video to capture
964      * @throws IllegalStateException if it is called after
965      * prepare() or before setOutputFormat().
966      *
967      * NOTE: On some devices that have auto-frame rate, this sets the
968      * maximum frame rate, not a constant frame rate. Actual frame rate
969      * will vary according to lighting conditions.
970      */
setVideoFrameRate(int rate)971     public native void setVideoFrameRate(int rate) throws IllegalStateException;
972 
973     /**
974      * Sets the maximum duration (in ms) of the recording session.
975      * Call this after setOutputFormat() but before prepare().
976      * After recording reaches the specified duration, a notification
977      * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
978      * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
979      * and recording will be stopped. Stopping happens asynchronously, there
980      * is no guarantee that the recorder will have stopped by the time the
981      * listener is notified.
982      *
983      * <p>When using MPEG-4 container ({@link #setOutputFormat(int)} with
984      * {@link OutputFormat#MPEG_4}), it is recommended to set maximum duration that fits the use
985      * case. Setting a larger than required duration may result in a larger than needed output file
986      * because of space reserved for MOOV box expecting large movie data in this recording session.
987      *  Unused space of MOOV box is turned into FREE box in the output file.</p>
988      *
989      * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
990      *
991      */
setMaxDuration(int max_duration_ms)992     public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
993 
994     /**
995      * Sets the maximum filesize (in bytes) of the recording session.
996      * Call this after setOutputFormat() but before prepare().
997      * After recording reaches the specified filesize, a notification
998      * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
999      * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
1000      * and recording will be stopped. Stopping happens asynchronously, there
1001      * is no guarantee that the recorder will have stopped by the time the
1002      * listener is notified.
1003      *
1004      * <p>When using MPEG-4 container ({@link #setOutputFormat(int)} with
1005      * {@link OutputFormat#MPEG_4}), it is recommended to set maximum filesize that fits the use
1006      * case. Setting a larger than required filesize may result in a larger than needed output file
1007      * because of space reserved for MOOV box expecting large movie data in this recording session.
1008      * Unused space of MOOV box is turned into FREE box in the output file.</p>
1009      *
1010      * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
1011      *
1012      */
setMaxFileSize(long max_filesize_bytes)1013     public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
1014 
1015     /**
1016      * Sets the audio encoder to be used for recording. If this method is not
1017      * called, the output file will not contain an audio track. Call this after
1018      * setOutputFormat() but before prepare().
1019      *
1020      * @param audio_encoder the audio encoder to use.
1021      * @throws IllegalStateException if it is called before
1022      * setOutputFormat() or after prepare().
1023      * @see android.media.MediaRecorder.AudioEncoder
1024      */
setAudioEncoder(@udioEncoderValues int audio_encoder)1025     public native void setAudioEncoder(@AudioEncoderValues int audio_encoder)
1026             throws IllegalStateException;
1027 
1028     /**
1029      * Sets the video encoder to be used for recording. If this method is not
1030      * called, the output file will not contain an video track. Call this after
1031      * setOutputFormat() and before prepare().
1032      *
1033      * @param video_encoder the video encoder to use.
1034      * @throws IllegalStateException if it is called before
1035      * setOutputFormat() or after prepare()
1036      * @see android.media.MediaRecorder.VideoEncoder
1037      */
setVideoEncoder(@ideoEncoderValues int video_encoder)1038     public native void setVideoEncoder(@VideoEncoderValues int video_encoder)
1039             throws IllegalStateException;
1040 
1041     /**
1042      * Sets the audio sampling rate for recording. Call this method before prepare().
1043      * Prepare() may perform additional checks on the parameter to make sure whether
1044      * the specified audio sampling rate is applicable. The sampling rate really depends
1045      * on the format for the audio recording, as well as the capabilities of the platform.
1046      * For instance, the sampling rate supported by AAC audio coding standard ranges
1047      * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
1048      * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
1049      * standard for the supported audio sampling rate.
1050      *
1051      * @param samplingRate the sampling rate for audio in samples per second.
1052      */
setAudioSamplingRate(int samplingRate)1053     public void setAudioSamplingRate(int samplingRate) {
1054         if (samplingRate <= 0) {
1055             throw new IllegalArgumentException("Audio sampling rate is not positive");
1056         }
1057         setParameter("audio-param-sampling-rate=" + samplingRate);
1058     }
1059 
1060     /**
1061      * Sets the number of audio channels for recording. Call this method before prepare().
1062      * Prepare() may perform additional checks on the parameter to make sure whether the
1063      * specified number of audio channels are applicable.
1064      *
1065      * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
1066      * (stereo).
1067      */
setAudioChannels(int numChannels)1068     public void setAudioChannels(int numChannels) {
1069         if (numChannels <= 0) {
1070             throw new IllegalArgumentException("Number of channels is not positive");
1071         }
1072         mChannelCount = numChannels;
1073         setParameter("audio-param-number-of-channels=" + numChannels);
1074     }
1075 
1076     /**
1077      * Sets the audio encoding bit rate for recording. Call this method before prepare().
1078      * Prepare() may perform additional checks on the parameter to make sure whether the
1079      * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
1080      * internally to ensure the audio recording can proceed smoothly based on the
1081      * capabilities of the platform.
1082      *
1083      * @param bitRate the audio encoding bit rate in bits per second.
1084      */
setAudioEncodingBitRate(int bitRate)1085     public void setAudioEncodingBitRate(int bitRate) {
1086         if (bitRate <= 0) {
1087             throw new IllegalArgumentException("Audio encoding bit rate is not positive");
1088         }
1089         setParameter("audio-param-encoding-bitrate=" + bitRate);
1090     }
1091 
1092     /**
1093      * Sets the video encoding bit rate for recording. Call this method before prepare().
1094      * Prepare() may perform additional checks on the parameter to make sure whether the
1095      * specified bit rate is applicable, and sometimes the passed bitRate will be
1096      * clipped internally to ensure the video recording can proceed smoothly based on
1097      * the capabilities of the platform.
1098      *
1099      * <p>
1100      * NB: the actual bitrate and other encoding characteristics may be affected by
1101      * the minimum quality floor behavior introduced in
1102      * {@link android.os.Build.VERSION_CODES#S}. More detail on how and where this
1103      * impacts video encoding can be found in the
1104      * {@link MediaCodec} page and looking for "quality floor" (near the top of the page).
1105      *
1106      * @param bitRate the video encoding bit rate in bits per second.
1107      */
setVideoEncodingBitRate(int bitRate)1108     public void setVideoEncodingBitRate(int bitRate) {
1109         if (bitRate <= 0) {
1110             throw new IllegalArgumentException("Video encoding bit rate is not positive");
1111         }
1112         setParameter("video-param-encoding-bitrate=" + bitRate);
1113     }
1114 
1115     /**
1116      * Sets the desired video encoding profile and level for recording. The profile and level
1117      * must be valid for the video encoder set by {@link #setVideoEncoder}. This method can
1118      * called before or after {@link #setVideoEncoder} but it must be called before {@link #prepare}.
1119      * {@code prepare()} may perform additional checks on the parameter to make sure that the specified
1120      * profile and level are applicable, and sometimes the passed profile or level will be
1121      * discarded due to codec capablity or to ensure the video recording can proceed smoothly
1122      * based on the capabilities of the platform. <br>Application can also use the
1123      * {@link MediaCodecInfo.CodecCapabilities#profileLevels} to query applicable combination of profile
1124      * and level for the corresponding format. Note that the requested profile/level may not be supported by
1125      * the codec that is actually being used by this MediaRecorder instance.
1126      * @param profile declared in {@link MediaCodecInfo.CodecProfileLevel}.
1127      * @param level declared in {@link MediaCodecInfo.CodecProfileLevel}.
1128      * @throws IllegalArgumentException when an invalid profile or level value is used.
1129      */
setVideoEncodingProfileLevel(int profile, int level)1130     public void setVideoEncodingProfileLevel(int profile, int level) {
1131         if (profile < 0)  {
1132             throw new IllegalArgumentException("Video encoding profile is not positive");
1133         }
1134         if (level < 0)  {
1135             throw new IllegalArgumentException("Video encoding level is not positive");
1136         }
1137         setParameter("video-param-encoder-profile=" + profile);
1138         setParameter("video-param-encoder-level=" + level);
1139     }
1140 
1141     /**
1142      * Currently not implemented. It does nothing.
1143      * @deprecated Time lapse mode video recording using camera still image capture
1144      * is not desirable, and will not be supported.
1145      * @hide
1146      */
setAuxiliaryOutputFile(FileDescriptor fd)1147     public void setAuxiliaryOutputFile(FileDescriptor fd)
1148     {
1149         Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
1150     }
1151 
1152     /**
1153      * Currently not implemented. It does nothing.
1154      * @deprecated Time lapse mode video recording using camera still image capture
1155      * is not desirable, and will not be supported.
1156      * @hide
1157      */
setAuxiliaryOutputFile(String path)1158     public void setAuxiliaryOutputFile(String path)
1159     {
1160         Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
1161     }
1162 
1163     /**
1164      * Pass in the file descriptor of the file to be written. Call this after
1165      * setOutputFormat() but before prepare().
1166      *
1167      * @param fd an open file descriptor to be written into.
1168      * @throws IllegalStateException if it is called before
1169      * setOutputFormat() or after prepare()
1170      */
setOutputFile(FileDescriptor fd)1171     public void setOutputFile(FileDescriptor fd) throws IllegalStateException
1172     {
1173         mPath = null;
1174         mFile = null;
1175         mFd = fd;
1176     }
1177 
1178     /**
1179      * Pass in the file object to be written. Call this after setOutputFormat() but before prepare().
1180      * File should be seekable. After setting the next output file, application should not use the
1181      * file until {@link #stop}. Application is responsible for cleaning up unused files after
1182      * {@link #stop} is called.
1183      *
1184      * @param file the file object to be written into.
1185      */
setOutputFile(File file)1186     public void setOutputFile(File file)
1187     {
1188         mPath = null;
1189         mFd = null;
1190         mFile = file;
1191     }
1192 
1193     /**
1194      * Sets the next output file descriptor to be used when the maximum filesize is reached
1195      * on the prior output {@link #setOutputFile} or {@link #setNextOutputFile}). File descriptor
1196      * must be seekable and writable. After setting the next output file, application should not
1197      * use the file referenced by this file descriptor until {@link #stop}. It is the application's
1198      * responsibility to close the file descriptor. It is safe to do so as soon as this call returns.
1199      * Application must call this after receiving on the
1200      * {@link android.media.MediaRecorder.OnInfoListener} a "what" code of
1201      * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING} and before receiving a "what" code of
1202      * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}. The file is not used until switching to
1203      * that output. Application will receive{@link #MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED}
1204      * when the next output file is used. Application will not be able to set a new output file if
1205      * the previous one has not been used. Application is responsible for cleaning up unused files
1206      * after {@link #stop} is called.
1207      *
1208      * @param fd an open file descriptor to be written into.
1209      * @throws IllegalStateException if it is called before prepare().
1210      * @throws IOException if setNextOutputFile fails otherwise.
1211      */
setNextOutputFile(FileDescriptor fd)1212     public void setNextOutputFile(FileDescriptor fd) throws IOException
1213     {
1214         _setNextOutputFile(fd);
1215     }
1216 
1217     /**
1218      * Sets the path of the output file to be produced. Call this after
1219      * setOutputFormat() but before prepare().
1220      *
1221      * @param path The pathname to use.
1222      * @throws IllegalStateException if it is called before
1223      * setOutputFormat() or after prepare()
1224      */
setOutputFile(String path)1225     public void setOutputFile(String path) throws IllegalStateException
1226     {
1227         mFd = null;
1228         mFile = null;
1229         mPath = path;
1230     }
1231 
1232     /**
1233      * Sets the next output file to be used when the maximum filesize is reached on the prior
1234      * output {@link #setOutputFile} or {@link #setNextOutputFile}). File should be seekable.
1235      * After setting the next output file, application should not use the file until {@link #stop}.
1236      * Application must call this after receiving on the
1237      * {@link android.media.MediaRecorder.OnInfoListener} a "what" code of
1238      * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING} and before receiving a "what" code of
1239      * {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}. The file is not used until switching to
1240      * that output. Application will receive {@link #MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED}
1241      * when the next output file is used. Application will not be able to set a new output file if
1242      * the previous one has not been used. Application is responsible for cleaning up unused files
1243      * after {@link #stop} is called.
1244      *
1245      * @param  file The file to use.
1246      * @throws IllegalStateException if it is called before prepare().
1247      * @throws IOException if setNextOutputFile fails otherwise.
1248      */
setNextOutputFile(File file)1249     public void setNextOutputFile(File file) throws IOException
1250     {
1251         RandomAccessFile f = new RandomAccessFile(file, "rw");
1252         try {
1253             _setNextOutputFile(f.getFD());
1254         } finally {
1255             f.close();
1256         }
1257     }
1258 
1259     // native implementation
_setOutputFile(FileDescriptor fd)1260     private native void _setOutputFile(FileDescriptor fd) throws IllegalStateException, IOException;
_setNextOutputFile(FileDescriptor fd)1261     private native void _setNextOutputFile(FileDescriptor fd) throws IllegalStateException, IOException;
1262     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
_prepare()1263     private native void _prepare() throws IllegalStateException, IOException;
1264 
1265     /**
1266      * Prepares the recorder to begin capturing and encoding data. This method
1267      * must be called after setting up the desired audio and video sources,
1268      * encoders, file format, etc., but before start().
1269      *
1270      * @throws IllegalStateException if it is called after
1271      * start() or before setOutputFormat().
1272      * @throws IOException if prepare fails otherwise.
1273      */
prepare()1274     public void prepare() throws IllegalStateException, IOException
1275     {
1276         if (mPath != null) {
1277             RandomAccessFile file = new RandomAccessFile(mPath, "rw");
1278             try {
1279                 _setOutputFile(file.getFD());
1280             } finally {
1281                 file.close();
1282             }
1283         } else if (mFd != null) {
1284             _setOutputFile(mFd);
1285         } else if (mFile != null) {
1286             RandomAccessFile file = new RandomAccessFile(mFile, "rw");
1287             try {
1288                 _setOutputFile(file.getFD());
1289             } finally {
1290                 file.close();
1291             }
1292         } else {
1293             throw new IOException("No valid output file");
1294         }
1295 
1296         _prepare();
1297     }
1298 
1299     /**
1300      * Begins capturing and encoding data to the file specified with
1301      * setOutputFile(). Call this after prepare().
1302      *
1303      * <p>Since API level 13, if applications set a camera via
1304      * {@link #setCamera(Camera)}, the apps can use the camera after this method
1305      * call. The apps do not need to lock the camera again. However, if this
1306      * method fails, the apps should still lock the camera back. The apps should
1307      * not start another recording session during recording.
1308      *
1309      * @throws IllegalStateException if it is called before
1310      * prepare() or when the camera is already in use by another app.
1311      */
start()1312     public native void start() throws IllegalStateException;
1313 
1314     /**
1315      * Stops recording. Call this after start(). Once recording is stopped,
1316      * you will have to configure it again as if it has just been constructed.
1317      * Note that a RuntimeException is intentionally thrown to the
1318      * application, if no valid audio/video data has been received when stop()
1319      * is called. This happens if stop() is called immediately after
1320      * start(). The failure lets the application take action accordingly to
1321      * clean up the output file (delete the output file, for instance), since
1322      * the output file is not properly constructed when this happens.
1323      *
1324      * @throws IllegalStateException if it is called before start()
1325      */
stop()1326     public native void stop() throws IllegalStateException;
1327 
1328     /**
1329      * Pauses recording. Call this after start(). You may resume recording
1330      * with resume() without reconfiguration, as opposed to stop(). It does
1331      * nothing if the recording is already paused.
1332      *
1333      * When the recording is paused and resumed, the resulting output would
1334      * be as if nothing happend during paused period, immediately switching
1335      * to the resumed scene.
1336      *
1337      * @throws IllegalStateException if it is called before start() or after
1338      * stop()
1339      */
pause()1340     public native void pause() throws IllegalStateException;
1341 
1342     /**
1343      * Resumes recording. Call this after start(). It does nothing if the
1344      * recording is not paused.
1345      *
1346      * @throws IllegalStateException if it is called before start() or after
1347      * stop()
1348      * @see android.media.MediaRecorder#pause
1349      */
resume()1350     public native void resume() throws IllegalStateException;
1351 
1352     /**
1353      * Restarts the MediaRecorder to its idle state. After calling
1354      * this method, you will have to configure it again as if it had just been
1355      * constructed.
1356      */
reset()1357     public void reset() {
1358         native_reset();
1359 
1360         // make sure none of the listeners get called anymore
1361         mEventHandler.removeCallbacksAndMessages(null);
1362     }
1363 
1364     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
native_reset()1365     private native void native_reset();
1366 
1367     /**
1368      * Returns the maximum absolute amplitude that was sampled since the last
1369      * call to this method. Call this only after the setAudioSource().
1370      *
1371      * @return the maximum absolute amplitude measured since the last call, or
1372      * 0 when called for the first time
1373      * @throws IllegalStateException if it is called before
1374      * the audio source has been set.
1375      */
getMaxAmplitude()1376     public native int getMaxAmplitude() throws IllegalStateException;
1377 
1378     /* Do not change this value without updating its counterpart
1379      * in include/media/mediarecorder.h or mediaplayer.h!
1380      */
1381     /** Unspecified media recorder error.
1382      * @see android.media.MediaRecorder.OnErrorListener
1383      */
1384     public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
1385     /** Media server died. In this case, the application must release the
1386      * MediaRecorder object and instantiate a new one.
1387      * @see android.media.MediaRecorder.OnErrorListener
1388      */
1389     public static final int MEDIA_ERROR_SERVER_DIED = 100;
1390 
1391     /**
1392      * Interface definition for a callback to be invoked when an error
1393      * occurs while recording.
1394      */
1395     public interface OnErrorListener
1396     {
1397         /**
1398          * Called when an error occurs while recording.
1399          *
1400          * @param mr the MediaRecorder that encountered the error
1401          * @param what    the type of error that has occurred:
1402          * <ul>
1403          * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
1404          * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1405          * </ul>
1406          * @param extra   an extra code, specific to the error type
1407          */
onError(MediaRecorder mr, int what, int extra)1408         void onError(MediaRecorder mr, int what, int extra);
1409     }
1410 
1411     /**
1412      * Register a callback to be invoked when an error occurs while
1413      * recording.
1414      *
1415      * @param l the callback that will be run
1416      */
setOnErrorListener(OnErrorListener l)1417     public void setOnErrorListener(OnErrorListener l)
1418     {
1419         mOnErrorListener = l;
1420     }
1421 
1422     /* Do not change these values without updating their counterparts
1423      * in include/media/mediarecorder.h!
1424      */
1425     /** Unspecified media recorder info.
1426      * @see android.media.MediaRecorder.OnInfoListener
1427      */
1428     public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
1429     /** A maximum duration had been setup and has now been reached.
1430      * @see android.media.MediaRecorder.OnInfoListener
1431      */
1432     public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
1433     /** A maximum filesize had been setup and has now been reached.
1434      * Note: This event will not be sent if application already set
1435      * next output file through {@link #setNextOutputFile}.
1436      * @see android.media.MediaRecorder.OnInfoListener
1437      */
1438     public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
1439     /** A maximum filesize had been setup and current recorded file size
1440      * has reached 90% of the limit. This is sent once per file upon
1441      * reaching/passing the 90% limit. To continue the recording, applicaiton
1442      * should use {@link #setNextOutputFile} to set the next output file.
1443      * Otherwise, recording will stop when reaching maximum file size.
1444      * @see android.media.MediaRecorder.OnInfoListener
1445      */
1446     public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING = 802;
1447     /** A maximum filesize had been reached and MediaRecorder has switched
1448      * output to a new file set by application {@link #setNextOutputFile}.
1449      * For best practice, application should use this event to keep track
1450      * of whether the file previously set has been used or not.
1451      * @see android.media.MediaRecorder.OnInfoListener
1452      */
1453     public static final int MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED = 803;
1454 
1455     /** informational events for individual tracks, for testing purpose.
1456      * The track informational event usually contains two parts in the ext1
1457      * arg of the onInfo() callback: bit 31-28 contains the track id; and
1458      * the rest of the 28 bits contains the informational event defined here.
1459      * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
1460      * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
1461      * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
1462      * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
1463      * application should extract the track id and the type of informational
1464      * event from ext1, accordingly.
1465      *
1466      * FIXME:
1467      * Please update the comment for onInfo also when these
1468      * events are unhidden so that application knows how to extract the track
1469      * id and the informational event type from onInfo callback.
1470      *
1471      * {@hide}
1472      */
1473     public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
1474     /** Signal the completion of the track for the recording session.
1475      * {@hide}
1476      */
1477     public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
1478     /** Indicate the recording progress in time (ms) during recording.
1479      * {@hide}
1480      */
1481     public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
1482     /** Indicate the track type: 0 for Audio and 1 for Video.
1483      * {@hide}
1484      */
1485     public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
1486     /** Provide the track duration information.
1487      * {@hide}
1488      */
1489     public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
1490     /** Provide the max chunk duration in time (ms) for the given track.
1491      * {@hide}
1492      */
1493     public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
1494     /** Provide the total number of recordd frames.
1495      * {@hide}
1496      */
1497     public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
1498     /** Provide the max spacing between neighboring chunks for the given track.
1499      * {@hide}
1500      */
1501     public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
1502     /** Provide the elapsed time measuring from the start of the recording
1503      * till the first output frame of the given track is received, excluding
1504      * any intentional start time offset of a recording session for the
1505      * purpose of eliminating the recording sound in the recorded file.
1506      * {@hide}
1507      */
1508     public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
1509     /** Provide the start time difference (delay) betweeen this track and
1510      * the start of the movie.
1511      * {@hide}
1512      */
1513     public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
1514     /** Provide the total number of data (in kilo-bytes) encoded.
1515      * {@hide}
1516      */
1517     public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
1518     /**
1519      * {@hide}
1520      */
1521     public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
1522 
1523 
1524     /**
1525      * Interface definition of a callback to be invoked to communicate some
1526      * info and/or warning about the recording.
1527      */
1528     public interface OnInfoListener
1529     {
1530         /**
1531          * Called to indicate an info or a warning during recording.
1532          *
1533          * @param mr   the MediaRecorder the info pertains to
1534          * @param what the type of info or warning that has occurred
1535          * <ul>
1536          * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
1537          * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
1538          * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
1539          * </ul>
1540          * @param extra   an extra code, specific to the info type
1541          */
onInfo(MediaRecorder mr, int what, int extra)1542         void onInfo(MediaRecorder mr, int what, int extra);
1543     }
1544 
1545     /**
1546      * Register a callback to be invoked when an informational event occurs while
1547      * recording.
1548      *
1549      * @param listener the callback that will be run
1550      */
setOnInfoListener(OnInfoListener listener)1551     public void setOnInfoListener(OnInfoListener listener)
1552     {
1553         mOnInfoListener = listener;
1554     }
1555 
1556     private class EventHandler extends Handler
1557     {
1558         private MediaRecorder mMediaRecorder;
1559 
EventHandler(MediaRecorder mr, Looper looper)1560         public EventHandler(MediaRecorder mr, Looper looper) {
1561             super(looper);
1562             mMediaRecorder = mr;
1563         }
1564 
1565         /* Do not change these values without updating their counterparts
1566          * in include/media/mediarecorder.h!
1567          */
1568         private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
1569         private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
1570         private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
1571         private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
1572 
1573         /* Events related to individual tracks */
1574         private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
1575         private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
1576         private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
1577         private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
1578 
1579         private static final int MEDIA_RECORDER_AUDIO_ROUTING_CHANGED  = 10000;
1580 
1581         @Override
handleMessage(Message msg)1582         public void handleMessage(Message msg) {
1583             if (mMediaRecorder.mNativeContext == 0) {
1584                 Log.w(TAG, "mediarecorder went away with unhandled events");
1585                 return;
1586             }
1587             switch(msg.what) {
1588             case MEDIA_RECORDER_EVENT_ERROR:
1589             case MEDIA_RECORDER_TRACK_EVENT_ERROR:
1590                 if (mOnErrorListener != null)
1591                     mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
1592 
1593                 return;
1594 
1595             case MEDIA_RECORDER_EVENT_INFO:
1596             case MEDIA_RECORDER_TRACK_EVENT_INFO:
1597                 if (mOnInfoListener != null)
1598                     mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
1599 
1600                 return;
1601 
1602             case MEDIA_RECORDER_AUDIO_ROUTING_CHANGED:
1603                 AudioManager.resetAudioPortGeneration();
1604                 synchronized (mRoutingChangeListeners) {
1605                     for (NativeRoutingEventHandlerDelegate delegate
1606                             : mRoutingChangeListeners.values()) {
1607                         delegate.notifyClient();
1608                     }
1609                 }
1610                 return;
1611 
1612             default:
1613                 Log.e(TAG, "Unknown message type " + msg.what);
1614                 return;
1615             }
1616         }
1617     }
1618 
1619     //--------------------------------------------------------------------------
1620     // Explicit Routing
1621     //--------------------
1622     private AudioDeviceInfo mPreferredDevice = null;
1623 
1624     /**
1625      * Specifies an audio device (via an {@link AudioDeviceInfo} object) to route
1626      * the input from this MediaRecorder.
1627      * @param deviceInfo The {@link AudioDeviceInfo} specifying the audio source.
1628      *  If deviceInfo is null, default routing is restored.
1629      * @return true if succesful, false if the specified {@link AudioDeviceInfo} is non-null and
1630      * does not correspond to a valid audio input device.
1631      */
1632     @Override
setPreferredDevice(AudioDeviceInfo deviceInfo)1633     public boolean setPreferredDevice(AudioDeviceInfo deviceInfo) {
1634         if (deviceInfo != null && !deviceInfo.isSource()) {
1635             return false;
1636         }
1637         int preferredDeviceId = deviceInfo != null ? deviceInfo.getId() : 0;
1638         boolean status = native_setInputDevice(preferredDeviceId);
1639         if (status == true) {
1640             synchronized (this) {
1641                 mPreferredDevice = deviceInfo;
1642             }
1643         }
1644         return status;
1645     }
1646 
1647     /**
1648      * Returns the selected input device specified by {@link #setPreferredDevice}. Note that this
1649      * is not guaranteed to correspond to the actual device being used for recording.
1650      */
1651     @Override
getPreferredDevice()1652     public AudioDeviceInfo getPreferredDevice() {
1653         synchronized (this) {
1654             return mPreferredDevice;
1655         }
1656     }
1657 
1658     /**
1659      * Returns an {@link AudioDeviceInfo} identifying the current routing of this MediaRecorder
1660      * Note: The query is only valid if the MediaRecorder is currently recording.
1661      * If the recorder is not recording, the returned device can be null or correspond to previously
1662      * selected device when the recorder was last active.
1663      */
1664     @Override
getRoutedDevice()1665     public AudioDeviceInfo getRoutedDevice() {
1666         int deviceId = native_getRoutedDeviceId();
1667         if (deviceId == 0) {
1668             return null;
1669         }
1670         return AudioManager.getDeviceForPortId(deviceId, AudioManager.GET_DEVICES_INPUTS);
1671     }
1672 
1673     /*
1674      * Call BEFORE adding a routing callback handler or AFTER removing a routing callback handler.
1675      */
1676     @GuardedBy("mRoutingChangeListeners")
enableNativeRoutingCallbacksLocked(boolean enabled)1677     private void enableNativeRoutingCallbacksLocked(boolean enabled) {
1678         if (mRoutingChangeListeners.size() == 0) {
1679             native_enableDeviceCallback(enabled);
1680         }
1681     }
1682 
1683     /**
1684      * The list of AudioRouting.OnRoutingChangedListener interfaces added (with
1685      * {@link #addOnRoutingChangedListener(android.media.AudioRouting.OnRoutingChangedListener, Handler)}
1686      * by an app to receive (re)routing notifications.
1687      */
1688     @GuardedBy("mRoutingChangeListeners")
1689     private ArrayMap<AudioRouting.OnRoutingChangedListener,
1690             NativeRoutingEventHandlerDelegate> mRoutingChangeListeners = new ArrayMap<>();
1691 
1692     /**
1693      * Adds an {@link AudioRouting.OnRoutingChangedListener} to receive notifications of routing
1694      * changes on this MediaRecorder.
1695      * @param listener The {@link AudioRouting.OnRoutingChangedListener} interface to receive
1696      * notifications of rerouting events.
1697      * @param handler  Specifies the {@link Handler} object for the thread on which to execute
1698      * the callback. If <code>null</code>, the handler on the main looper will be used.
1699      */
1700     @Override
addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, Handler handler)1701     public void addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener,
1702                                             Handler handler) {
1703         synchronized (mRoutingChangeListeners) {
1704             if (listener != null && !mRoutingChangeListeners.containsKey(listener)) {
1705                 enableNativeRoutingCallbacksLocked(true);
1706                 mRoutingChangeListeners.put(
1707                         listener, new NativeRoutingEventHandlerDelegate(this, listener,
1708                                 handler != null ? handler : mEventHandler));
1709             }
1710         }
1711     }
1712 
1713     /**
1714      * Removes an {@link AudioRouting.OnRoutingChangedListener} which has been previously added
1715      * to receive rerouting notifications.
1716      * @param listener The previously added {@link AudioRouting.OnRoutingChangedListener} interface
1717      * to remove.
1718      */
1719     @Override
removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener)1720     public void removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener) {
1721         synchronized (mRoutingChangeListeners) {
1722             if (mRoutingChangeListeners.containsKey(listener)) {
1723                 mRoutingChangeListeners.remove(listener);
1724                 enableNativeRoutingCallbacksLocked(false);
1725             }
1726         }
1727     }
1728 
native_setInputDevice(int deviceId)1729     private native final boolean native_setInputDevice(int deviceId);
native_getRoutedDeviceId()1730     private native final int native_getRoutedDeviceId();
native_enableDeviceCallback(boolean enabled)1731     private native final void native_enableDeviceCallback(boolean enabled);
1732 
1733     //--------------------------------------------------------------------------
1734     // Microphone information
1735     //--------------------
1736     /**
1737      * Return A lists of {@link MicrophoneInfo} representing the active microphones.
1738      * By querying channel mapping for each active microphone, developer can know how
1739      * the microphone is used by each channels or a capture stream.
1740      *
1741      * @return a lists of {@link MicrophoneInfo} representing the active microphones
1742      * @throws IOException if an error occurs
1743      */
getActiveMicrophones()1744     public List<MicrophoneInfo> getActiveMicrophones() throws IOException {
1745         ArrayList<MicrophoneInfo> activeMicrophones = new ArrayList<>();
1746         int status = native_getActiveMicrophones(activeMicrophones);
1747         if (status != AudioManager.SUCCESS) {
1748             if (status != AudioManager.ERROR_INVALID_OPERATION) {
1749                 Log.e(TAG, "getActiveMicrophones failed:" + status);
1750             }
1751             Log.i(TAG, "getActiveMicrophones failed, fallback on routed device info");
1752         }
1753         AudioManager.setPortIdForMicrophones(activeMicrophones);
1754 
1755         // Use routed device when there is not information returned by hal.
1756         if (activeMicrophones.size() == 0) {
1757             AudioDeviceInfo device = getRoutedDevice();
1758             if (device != null) {
1759                 MicrophoneInfo microphone = AudioManager.microphoneInfoFromAudioDeviceInfo(device);
1760                 ArrayList<Pair<Integer, Integer>> channelMapping = new ArrayList<>();
1761                 for (int i = 0; i < mChannelCount; i++) {
1762                     channelMapping.add(new Pair(i, MicrophoneInfo.CHANNEL_MAPPING_DIRECT));
1763                 }
1764                 microphone.setChannelMapping(channelMapping);
1765                 activeMicrophones.add(microphone);
1766             }
1767         }
1768         return activeMicrophones;
1769     }
1770 
native_getActiveMicrophones( ArrayList<MicrophoneInfo> activeMicrophones)1771     private native final int native_getActiveMicrophones(
1772             ArrayList<MicrophoneInfo> activeMicrophones);
1773 
1774     //--------------------------------------------------------------------------
1775     // MicrophoneDirection
1776     //--------------------
1777     /**
1778      * Specifies the logical microphone (for processing).
1779      *
1780      * @param direction Direction constant.
1781      * @return true if sucessful.
1782      */
setPreferredMicrophoneDirection(@irectionMode int direction)1783     public boolean setPreferredMicrophoneDirection(@DirectionMode int direction) {
1784         return native_setPreferredMicrophoneDirection(direction) == 0;
1785     }
1786 
1787     /**
1788      * Specifies the zoom factor (i.e. the field dimension) for the selected microphone
1789      * (for processing). The selected microphone is determined by the use-case for the stream.
1790      *
1791      * @param zoom the desired field dimension of microphone capture. Range is from -1 (wide angle),
1792      * though 0 (no zoom) to 1 (maximum zoom).
1793      * @return true if sucessful.
1794      */
setPreferredMicrophoneFieldDimension( @loatRangefrom = -1.0, to = 1.0) float zoom)1795     public boolean setPreferredMicrophoneFieldDimension(
1796                             @FloatRange(from = -1.0, to = 1.0) float zoom) {
1797         Preconditions.checkArgument(
1798                 zoom >= -1 && zoom <= 1, "Argument must fall between -1 & 1 (inclusive)");
1799         return native_setPreferredMicrophoneFieldDimension(zoom) == 0;
1800     }
1801 
native_setPreferredMicrophoneDirection(int direction)1802     private native int native_setPreferredMicrophoneDirection(int direction);
native_setPreferredMicrophoneFieldDimension(float zoom)1803     private native int native_setPreferredMicrophoneFieldDimension(float zoom);
1804 
1805     //--------------------------------------------------------------------------
1806     // Implementation of AudioRecordingMonitor interface
1807     //--------------------
1808 
1809     AudioRecordingMonitorImpl mRecordingInfoImpl =
1810             new AudioRecordingMonitorImpl((AudioRecordingMonitorClient) this);
1811 
1812     /**
1813      * Register a callback to be notified of audio capture changes via a
1814      * {@link AudioManager.AudioRecordingCallback}. A callback is received when the capture path
1815      * configuration changes (pre-processing, format, sampling rate...) or capture is
1816      * silenced/unsilenced by the system.
1817      * @param executor {@link Executor} to handle the callbacks.
1818      * @param cb non-null callback to register
1819      */
registerAudioRecordingCallback(@onNull @allbackExecutor Executor executor, @NonNull AudioManager.AudioRecordingCallback cb)1820     public void registerAudioRecordingCallback(@NonNull @CallbackExecutor Executor executor,
1821             @NonNull AudioManager.AudioRecordingCallback cb) {
1822         mRecordingInfoImpl.registerAudioRecordingCallback(executor, cb);
1823     }
1824 
1825     /**
1826      * Unregister an audio recording callback previously registered with
1827      * {@link #registerAudioRecordingCallback(Executor, AudioManager.AudioRecordingCallback)}.
1828      * @param cb non-null callback to unregister
1829      */
unregisterAudioRecordingCallback(@onNull AudioManager.AudioRecordingCallback cb)1830     public void unregisterAudioRecordingCallback(@NonNull AudioManager.AudioRecordingCallback cb) {
1831         mRecordingInfoImpl.unregisterAudioRecordingCallback(cb);
1832     }
1833 
1834     /**
1835      * Returns the current active audio recording for this audio recorder.
1836      * @return a valid {@link AudioRecordingConfiguration} if this recorder is active
1837      * or null otherwise.
1838      * @see AudioRecordingConfiguration
1839      */
getActiveRecordingConfiguration()1840     public @Nullable AudioRecordingConfiguration getActiveRecordingConfiguration() {
1841         return mRecordingInfoImpl.getActiveRecordingConfiguration();
1842     }
1843 
1844     //---------------------------------------------------------
1845     // Implementation of AudioRecordingMonitorClient interface
1846     //--------------------
1847     /**
1848      * @hide
1849      */
getPortId()1850     public int getPortId() {
1851         if (mNativeContext == 0) {
1852             return 0;
1853         }
1854         return native_getPortId();
1855     }
1856 
native_getPortId()1857     private native int native_getPortId();
1858 
1859     /**
1860      * Called from native code when an interesting event happens.  This method
1861      * just uses the EventHandler system to post the event back to the main app thread.
1862      * We use a weak reference to the original MediaRecorder object so that the native
1863      * code is safe from the object disappearing from underneath it.  (This is
1864      * the cookie passed to native_setup().)
1865      */
postEventFromNative(Object mediarecorder_ref, int what, int arg1, int arg2, Object obj)1866     private static void postEventFromNative(Object mediarecorder_ref,
1867                                             int what, int arg1, int arg2, Object obj)
1868     {
1869         MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
1870         if (mr == null) {
1871             return;
1872         }
1873 
1874         if (mr.mEventHandler != null) {
1875             Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1876             mr.mEventHandler.sendMessage(m);
1877         }
1878     }
1879 
1880     /**
1881      * Releases resources associated with this MediaRecorder object.
1882      * It is good practice to call this method when you're done
1883      * using the MediaRecorder. In particular, whenever an Activity
1884      * of an application is paused (its onPause() method is called),
1885      * or stopped (its onStop() method is called), this method should be
1886      * invoked to release the MediaRecorder object, unless the application
1887      * has a special need to keep the object around. In addition to
1888      * unnecessary resources (such as memory and instances of codecs)
1889      * being held, failure to call this method immediately if a
1890      * MediaRecorder object is no longer needed may also lead to
1891      * continuous battery consumption for mobile devices, and recording
1892      * failure for other applications if no multiple instances of the
1893      * same codec are supported on a device. Even if multiple instances
1894      * of the same codec are supported, some performance degradation
1895      * may be expected when unnecessary multiple instances are used
1896      * at the same time.
1897      */
release()1898     public native void release();
1899 
1900     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
native_init()1901     private static native final void native_init();
1902 
1903     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R,
1904             publicAlternatives = "{@link MediaRecorder}")
native_setup(Object mediarecorderThis, String clientName, String opPackageName)1905     private void native_setup(Object mediarecorderThis,
1906             String clientName, String opPackageName) throws IllegalStateException {
1907         AttributionSource attributionSource = AttributionSource.myAttributionSource()
1908                 .withPackageName(opPackageName);
1909         try (ScopedParcelState attributionSourceState = attributionSource.asScopedParcelState()) {
1910             native_setup(mediarecorderThis, clientName, attributionSourceState.getParcel());
1911         }
1912     }
1913 
native_setup(Object mediarecorderThis, String clientName, @NonNull Parcel attributionSource)1914     private native void native_setup(Object mediarecorderThis,
1915             String clientName, @NonNull Parcel attributionSource)
1916             throws IllegalStateException;
1917 
1918     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
native_finalize()1919     private native void native_finalize();
1920 
1921     @UnsupportedAppUsage
setParameter(String nameValuePair)1922     private native void setParameter(String nameValuePair);
1923 
1924     /**
1925      *  Return Metrics data about the current Mediarecorder instance.
1926      *
1927      * @return a {@link PersistableBundle} containing the set of attributes and values
1928      * available for the media being generated by this instance of
1929      * MediaRecorder.
1930      * The attributes are descibed in {@link MetricsConstants}.
1931      *
1932      *  Additional vendor-specific fields may also be present in
1933      *  the return value.
1934      */
getMetrics()1935     public PersistableBundle getMetrics() {
1936         PersistableBundle bundle = native_getMetrics();
1937         return bundle;
1938     }
1939 
native_getMetrics()1940     private native PersistableBundle native_getMetrics();
1941 
1942     @Override
finalize()1943     protected void finalize() { native_finalize(); }
1944 
1945     public final static class MetricsConstants
1946     {
MetricsConstants()1947         private MetricsConstants() {}
1948 
1949         /**
1950          * Key to extract the audio bitrate
1951          * from the {@link MediaRecorder#getMetrics} return.
1952          * The value is an integer.
1953          */
1954         public static final String AUDIO_BITRATE = "android.media.mediarecorder.audio-bitrate";
1955 
1956         /**
1957          * Key to extract the number of audio channels
1958          * from the {@link MediaRecorder#getMetrics} return.
1959          * The value is an integer.
1960          */
1961         public static final String AUDIO_CHANNELS = "android.media.mediarecorder.audio-channels";
1962 
1963         /**
1964          * Key to extract the audio samplerate
1965          * from the {@link MediaRecorder#getMetrics} return.
1966          * The value is an integer.
1967          */
1968         public static final String AUDIO_SAMPLERATE = "android.media.mediarecorder.audio-samplerate";
1969 
1970         /**
1971          * Key to extract the audio timescale
1972          * from the {@link MediaRecorder#getMetrics} return.
1973          * The value is an integer.
1974          */
1975         public static final String AUDIO_TIMESCALE = "android.media.mediarecorder.audio-timescale";
1976 
1977         /**
1978          * Key to extract the video capture frame rate
1979          * from the {@link MediaRecorder#getMetrics} return.
1980          * The value is a double.
1981          */
1982         public static final String CAPTURE_FPS = "android.media.mediarecorder.capture-fps";
1983 
1984         /**
1985          * Key to extract the video capture framerate enable value
1986          * from the {@link MediaRecorder#getMetrics} return.
1987          * The value is an integer.
1988          */
1989         public static final String CAPTURE_FPS_ENABLE = "android.media.mediarecorder.capture-fpsenable";
1990 
1991         /**
1992          * Key to extract the intended playback frame rate
1993          * from the {@link MediaRecorder#getMetrics} return.
1994          * The value is an integer.
1995          */
1996         public static final String FRAMERATE = "android.media.mediarecorder.frame-rate";
1997 
1998         /**
1999          * Key to extract the height (in pixels) of the captured video
2000          * from the {@link MediaRecorder#getMetrics} return.
2001          * The value is an integer.
2002          */
2003         public static final String HEIGHT = "android.media.mediarecorder.height";
2004 
2005         /**
2006          * Key to extract the recorded movies time units
2007          * from the {@link MediaRecorder#getMetrics} return.
2008          * The value is an integer.
2009          * A value of 1000 indicates that the movie's timing is in milliseconds.
2010          */
2011         public static final String MOVIE_TIMESCALE = "android.media.mediarecorder.movie-timescale";
2012 
2013         /**
2014          * Key to extract the rotation (in degrees) to properly orient the video
2015          * from the {@link MediaRecorder#getMetrics} return.
2016          * The value is an integer.
2017          */
2018         public static final String ROTATION = "android.media.mediarecorder.rotation";
2019 
2020         /**
2021          * Key to extract the video bitrate from being used
2022          * from the {@link MediaRecorder#getMetrics} return.
2023          * The value is an integer.
2024          */
2025         public static final String VIDEO_BITRATE = "android.media.mediarecorder.video-bitrate";
2026 
2027         /**
2028          * Key to extract the value for how often video iframes are generated
2029          * from the {@link MediaRecorder#getMetrics} return.
2030          * The value is an integer.
2031          */
2032         public static final String VIDEO_IFRAME_INTERVAL = "android.media.mediarecorder.video-iframe-interval";
2033 
2034         /**
2035          * Key to extract the video encoding level
2036          * from the {@link MediaRecorder#getMetrics} return.
2037          * The value is an integer.
2038          */
2039         public static final String VIDEO_LEVEL = "android.media.mediarecorder.video-encoder-level";
2040 
2041         /**
2042          * Key to extract the video encoding profile
2043          * from the {@link MediaRecorder#getMetrics} return.
2044          * The value is an integer.
2045          */
2046         public static final String VIDEO_PROFILE = "android.media.mediarecorder.video-encoder-profile";
2047 
2048         /**
2049          * Key to extract the recorded video time units
2050          * from the {@link MediaRecorder#getMetrics} return.
2051          * The value is an integer.
2052          * A value of 1000 indicates that the video's timing is in milliseconds.
2053          */
2054         public static final String VIDEO_TIMESCALE = "android.media.mediarecorder.video-timescale";
2055 
2056         /**
2057          * Key to extract the width (in pixels) of the captured video
2058          * from the {@link MediaRecorder#getMetrics} return.
2059          * The value is an integer.
2060          */
2061         public static final String WIDTH = "android.media.mediarecorder.width";
2062 
2063     }
2064 }
2065