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