1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.media;
18 
19 import android.annotation.IntDef;
20 import android.annotation.NonNull;
21 import android.annotation.UnsupportedAppUsage;
22 import android.media.MediaCodec;
23 import android.media.MediaCodec.BufferInfo;
24 
25 import dalvik.system.CloseGuard;
26 
27 import java.io.FileDescriptor;
28 import java.io.IOException;
29 import java.io.RandomAccessFile;
30 import java.lang.annotation.Retention;
31 import java.lang.annotation.RetentionPolicy;
32 import java.nio.ByteBuffer;
33 import java.util.Map;
34 
35 /**
36  * MediaMuxer facilitates muxing elementary streams. Currently MediaMuxer supports MP4, Webm
37  * and 3GP file as the output. It also supports muxing B-frames in MP4 since Android Nougat.
38  * <p>
39  * It is generally used like this:
40  *
41  * <pre>
42  * MediaMuxer muxer = new MediaMuxer("temp.mp4", OutputFormat.MUXER_OUTPUT_MPEG_4);
43  * // More often, the MediaFormat will be retrieved from MediaCodec.getOutputFormat()
44  * // or MediaExtractor.getTrackFormat().
45  * MediaFormat audioFormat = new MediaFormat(...);
46  * MediaFormat videoFormat = new MediaFormat(...);
47  * int audioTrackIndex = muxer.addTrack(audioFormat);
48  * int videoTrackIndex = muxer.addTrack(videoFormat);
49  * ByteBuffer inputBuffer = ByteBuffer.allocate(bufferSize);
50  * boolean finished = false;
51  * BufferInfo bufferInfo = new BufferInfo();
52  *
53  * muxer.start();
54  * while(!finished) {
55  *   // getInputBuffer() will fill the inputBuffer with one frame of encoded
56  *   // sample from either MediaCodec or MediaExtractor, set isAudioSample to
57  *   // true when the sample is audio data, set up all the fields of bufferInfo,
58  *   // and return true if there are no more samples.
59  *   finished = getInputBuffer(inputBuffer, isAudioSample, bufferInfo);
60  *   if (!finished) {
61  *     int currentTrackIndex = isAudioSample ? audioTrackIndex : videoTrackIndex;
62  *     muxer.writeSampleData(currentTrackIndex, inputBuffer, bufferInfo);
63  *   }
64  * };
65  * muxer.stop();
66  * muxer.release();
67  * </pre>
68  *
69 
70  <h4>Metadata Track</h4>
71  <p>
72   Per-frame metadata is useful in carrying extra information that correlated with video or audio to
73   facilitate offline processing, e.g. gyro signals from the sensor could help video stabilization when
74   doing offline processing. Metadata track is only supported in MP4 container. When adding a new
75   metadata track, track's mime format must start with prefix "application/", e.g. "applicaton/gyro".
76   Metadata's format/layout will be defined by the application. Writing metadata is nearly the same as
77   writing video/audio data except that the data will not be from mediacodec. Application just needs
78   to pass the bytebuffer that contains the metadata and also the associated timestamp to the
79   {@link #writeSampleData} api. The timestamp must be in the same time base as video and audio. The
80   generated MP4 file uses TextMetaDataSampleEntry defined in section 12.3.3.2 of the ISOBMFF to signal
81   the metadata's mime format. When using{@link android.media.MediaExtractor} to extract the file with
82   metadata track, the mime format of the metadata will be extracted into {@link android.media.MediaFormat}.
83 
84  <pre class=prettyprint>
85    MediaMuxer muxer = new MediaMuxer("temp.mp4", OutputFormat.MUXER_OUTPUT_MPEG_4);
86    // SetUp Video/Audio Tracks.
87    MediaFormat audioFormat = new MediaFormat(...);
88    MediaFormat videoFormat = new MediaFormat(...);
89    int audioTrackIndex = muxer.addTrack(audioFormat);
90    int videoTrackIndex = muxer.addTrack(videoFormat);
91 
92    // Setup Metadata Track
93    MediaFormat metadataFormat = new MediaFormat(...);
94    metadataFormat.setString(KEY_MIME, "application/gyro");
95    int metadataTrackIndex = muxer.addTrack(metadataFormat);
96 
97    muxer.start();
98    while(..) {
99        // Allocate bytebuffer and write gyro data(x,y,z) into it.
100        ByteBuffer metaData = ByteBuffer.allocate(bufferSize);
101        metaData.putFloat(x);
102        metaData.putFloat(y);
103        metaData.putFloat(z);
104        BufferInfo metaInfo = new BufferInfo();
105        // Associate this metadata with the video frame by setting
106        // the same timestamp as the video frame.
107        metaInfo.presentationTimeUs = currentVideoTrackTimeUs;
108        metaInfo.offset = 0;
109        metaInfo.flags = 0;
110        metaInfo.size = bufferSize;
111        muxer.writeSampleData(metadataTrackIndex, metaData, metaInfo);
112    };
113    muxer.stop();
114    muxer.release();
115  }</pre>
116 
117  <h2 id=History><a name="History"></a>Features and API History</h2>
118  <p>
119  The following table summarizes the feature support in different API version and containers.
120  For API version numbers, see {@link android.os.Build.VERSION_CODES}.
121 
122  <style>
123  .api > tr > th, .api > tr > td { text-align: center; padding: 4px 4px; }
124  .api > tr > th     { vertical-align: bottom; }
125  .api > tr > td     { vertical-align: middle; }
126  .sml > tr > th, .sml > tr > td { text-align: center; padding: 2px 4px; }
127  .fn { text-align: center; }
128  </style>
129 
130  <table align="right" style="width: 0%">
131   <thead>
132    <tbody class=api>
133     <tr><th>Symbol</th>
134     <th>Meaning</th></tr>
135    </tbody>
136   </thead>
137   <tbody class=sml>
138    <tr><td>&#9679;</td><td>Supported</td></tr>
139    <tr><td>&#9675;</td><td>Not supported</td></tr>
140    <tr><td>&#9639;</td><td>Supported in MP4/WebM/3GP</td></tr>
141    <tr><td>&#8277;</td><td>Only Supported in MP4</td></tr>
142   </tbody>
143  </table>
144 <table align="center" style="width: 100%;">
145   <thead class=api>
146    <tr>
147     <th rowspan=2>Feature</th>
148     <th colspan="24">SDK Version</th>
149    </tr>
150    <tr>
151     <th>18</th>
152     <th>19</th>
153     <th>20</th>
154     <th>21</th>
155     <th>22</th>
156     <th>23</th>
157     <th>24</th>
158     <th>25</th>
159     <th>26+</th>
160    </tr>
161   </thead>
162  <tbody class=api>
163    <tr>
164     <td align="center">MP4 container</td>
165     <td>&#9679;</td>
166     <td>&#9679;</td>
167     <td>&#9679;</td>
168     <td>&#9679;</td>
169     <td>&#9679;</td>
170     <td>&#9679;</td>
171     <td>&#9679;</td>
172     <td>&#9679;</td>
173     <td>&#9679;</td>
174    </tr>
175     <td align="center">WebM container</td>
176     <td>&#9675;</td>
177     <td>&#9675;</td>
178     <td>&#9675;</td>
179     <td>&#9679;</td>
180     <td>&#9679;</td>
181     <td>&#9679;</td>
182     <td>&#9679;</td>
183     <td>&#9679;</td>
184     <td>&#9679;</td>
185    </tr>
186     <td align="center">3GP container</td>
187     <td>&#9675;</td>
188     <td>&#9675;</td>
189     <td>&#9675;</td>
190     <td>&#9675;</td>
191     <td>&#9675;</td>
192     <td>&#9675;</td>
193     <td>&#9675;</td>
194     <td>&#9675;</td>
195     <td>&#9679;</td>
196    </tr>
197     <td align="center">Muxing B-Frames(bi-directional predicted frames)</td>
198     <td>&#9675;</td>
199     <td>&#9675;</td>
200     <td>&#9675;</td>
201     <td>&#9675;</td>
202     <td>&#9675;</td>
203     <td>&#9675;</td>
204     <td>&#8277;</td>
205     <td>&#8277;</td>
206     <td>&#8277;</td>
207    </tr>
208    </tr>
209     <td align="center">Muxing Single Video/Audio Track</td>
210     <td>&#9639;</td>
211     <td>&#9639;</td>
212     <td>&#9639;</td>
213     <td>&#9639;</td>
214     <td>&#9639;</td>
215     <td>&#9639;</td>
216     <td>&#9639;</td>
217     <td>&#9639;</td>
218     <td>&#9639;</td>
219    </tr>
220    </tr>
221     <td align="center">Muxing Multiple Video/Audio Tracks</td>
222     <td>&#9675;</td>
223     <td>&#9675;</td>
224     <td>&#9675;</td>
225     <td>&#9675;</td>
226     <td>&#9675;</td>
227     <td>&#9675;</td>
228     <td>&#9675;</td>
229     <td>&#9675;</td>
230     <td>&#8277;</td>
231    </tr>
232    </tr>
233     <td align="center">Muxing Metadata Tracks</td>
234     <td>&#9675;</td>
235     <td>&#9675;</td>
236     <td>&#9675;</td>
237     <td>&#9675;</td>
238     <td>&#9675;</td>
239     <td>&#9675;</td>
240     <td>&#9675;</td>
241     <td>&#9675;</td>
242     <td>&#8277;</td>
243    </tr>
244    </tbody>
245  </table>
246  */
247 
248 final public class MediaMuxer {
249 
250     static {
251         System.loadLibrary("media_jni");
252     }
253 
254     /**
255      * Defines the output format. These constants are used with constructor.
256      */
257     public static final class OutputFormat {
258         /* Do not change these values without updating their counterparts
259          * in include/media/stagefright/MediaMuxer.h!
260          */
OutputFormat()261         private OutputFormat() {}
262         /** @hide */
263         public static final int MUXER_OUTPUT_FIRST   = 0;
264         /** MPEG4 media file format*/
265         public static final int MUXER_OUTPUT_MPEG_4 = MUXER_OUTPUT_FIRST;
266         /** WEBM media file format*/
267         public static final int MUXER_OUTPUT_WEBM   = MUXER_OUTPUT_FIRST + 1;
268         /** 3GPP media file format*/
269         public static final int MUXER_OUTPUT_3GPP   = MUXER_OUTPUT_FIRST + 2;
270         /** HEIF media file format*/
271         public static final int MUXER_OUTPUT_HEIF   = MUXER_OUTPUT_FIRST + 3;
272         /** Ogg media file format*/
273         public static final int MUXER_OUTPUT_OGG   = MUXER_OUTPUT_FIRST + 4;
274         /** @hide */
275         public static final int MUXER_OUTPUT_LAST   = MUXER_OUTPUT_OGG;
276     };
277 
278     /** @hide */
279     @IntDef({
280         OutputFormat.MUXER_OUTPUT_MPEG_4,
281         OutputFormat.MUXER_OUTPUT_WEBM,
282         OutputFormat.MUXER_OUTPUT_3GPP,
283         OutputFormat.MUXER_OUTPUT_HEIF,
284         OutputFormat.MUXER_OUTPUT_OGG,
285     })
286     @Retention(RetentionPolicy.SOURCE)
287     public @interface Format {}
288 
289     // All the native functions are listed here.
290     @UnsupportedAppUsage
nativeSetup(@onNull FileDescriptor fd, int format)291     private static native long nativeSetup(@NonNull FileDescriptor fd, int format)
292             throws IllegalArgumentException, IOException;
293     @UnsupportedAppUsage
nativeRelease(long nativeObject)294     private static native void nativeRelease(long nativeObject);
nativeStart(long nativeObject)295     private static native void nativeStart(long nativeObject);
nativeStop(long nativeObject)296     private static native void nativeStop(long nativeObject);
nativeAddTrack( long nativeObject, @NonNull String[] keys, @NonNull Object[] values)297     private static native int nativeAddTrack(
298             long nativeObject, @NonNull String[] keys, @NonNull Object[] values);
nativeSetOrientationHint( long nativeObject, int degrees)299     private static native void nativeSetOrientationHint(
300             long nativeObject, int degrees);
nativeSetLocation(long nativeObject, int latitude, int longitude)301     private static native void nativeSetLocation(long nativeObject, int latitude, int longitude);
nativeWriteSampleData( long nativeObject, int trackIndex, @NonNull ByteBuffer byteBuf, int offset, int size, long presentationTimeUs, @MediaCodec.BufferFlag int flags)302     private static native void nativeWriteSampleData(
303             long nativeObject, int trackIndex, @NonNull ByteBuffer byteBuf,
304             int offset, int size, long presentationTimeUs, @MediaCodec.BufferFlag int flags);
305 
306     // Muxer internal states.
307     @UnsupportedAppUsage
308     private static final int MUXER_STATE_UNINITIALIZED  = -1;
309     private static final int MUXER_STATE_INITIALIZED    = 0;
310     @UnsupportedAppUsage
311     private static final int MUXER_STATE_STARTED        = 1;
312     @UnsupportedAppUsage
313     private static final int MUXER_STATE_STOPPED        = 2;
314 
315     @UnsupportedAppUsage
316     private int mState = MUXER_STATE_UNINITIALIZED;
317 
318     @UnsupportedAppUsage
319     private final CloseGuard mCloseGuard = CloseGuard.get();
320     private int mLastTrackIndex = -1;
321 
322     @UnsupportedAppUsage
323     private long mNativeObject;
324 
325     /**
326      * Constructor.
327      * Creates a media muxer that writes to the specified path.
328      * @param path The path of the output media file.
329      * @param format The format of the output media file.
330      * @see android.media.MediaMuxer.OutputFormat
331      * @throws IllegalArgumentException if path is invalid or format is not supported.
332      * @throws IOException if failed to open the file for write.
333      */
MediaMuxer(@onNull String path, @Format int format)334     public MediaMuxer(@NonNull String path, @Format int format) throws IOException {
335         if (path == null) {
336             throw new IllegalArgumentException("path must not be null");
337         }
338         // Use RandomAccessFile so we can open the file with RW access;
339         // RW access allows the native writer to memory map the output file.
340         RandomAccessFile file = null;
341         try {
342             file = new RandomAccessFile(path, "rws");
343             file.setLength(0);
344             FileDescriptor fd = file.getFD();
345             setUpMediaMuxer(fd, format);
346         } finally {
347             if (file != null) {
348                 file.close();
349             }
350         }
351     }
352 
353     /**
354      * Constructor.
355      * Creates a media muxer that writes to the specified FileDescriptor. File descriptor
356      * must be seekable and writable. Application should not use the file referenced
357      * by this file descriptor until {@link #stop}. It is the application's responsibility
358      * to close the file descriptor. It is safe to do so as soon as this call returns.
359      * @param fd The FileDescriptor of the output media file.
360      * @param format The format of the output media file.
361      * @see android.media.MediaMuxer.OutputFormat
362      * @throws IllegalArgumentException if fd is invalid or format is not supported.
363      * @throws IOException if failed to open the file for write.
364      */
MediaMuxer(@onNull FileDescriptor fd, @Format int format)365     public MediaMuxer(@NonNull FileDescriptor fd, @Format int format) throws IOException {
366         setUpMediaMuxer(fd, format);
367     }
368 
setUpMediaMuxer(@onNull FileDescriptor fd, @Format int format)369     private void setUpMediaMuxer(@NonNull FileDescriptor fd, @Format int format) throws IOException {
370         if (format < OutputFormat.MUXER_OUTPUT_FIRST || format > OutputFormat.MUXER_OUTPUT_LAST) {
371             throw new IllegalArgumentException("format: " + format + " is invalid");
372         }
373         mNativeObject = nativeSetup(fd, format);
374         mState = MUXER_STATE_INITIALIZED;
375         mCloseGuard.open("release");
376     }
377 
378     /**
379      * Sets the orientation hint for output video playback.
380      * <p>This method should be called before {@link #start}. Calling this
381      * method will not rotate the video frame when muxer is generating the file,
382      * but add a composition matrix containing the rotation angle in the output
383      * video if the output format is
384      * {@link OutputFormat#MUXER_OUTPUT_MPEG_4} so that a video player can
385      * choose the proper orientation for playback. Note that some video players
386      * may choose to ignore the composition matrix in a video during playback.
387      * By default, the rotation degree is 0.</p>
388      * @param degrees the angle to be rotated clockwise in degrees.
389      * The supported angles are 0, 90, 180, and 270 degrees.
390      * @throws IllegalArgumentException if degree is not supported.
391      * @throws IllegalStateException If this method is called after {@link #start}.
392      */
setOrientationHint(int degrees)393     public void setOrientationHint(int degrees) {
394         if (degrees != 0 && degrees != 90  && degrees != 180 && degrees != 270) {
395             throw new IllegalArgumentException("Unsupported angle: " + degrees);
396         }
397         if (mState == MUXER_STATE_INITIALIZED) {
398             nativeSetOrientationHint(mNativeObject, degrees);
399         } else {
400             throw new IllegalStateException("Can't set rotation degrees due" +
401                     " to wrong state.");
402         }
403     }
404 
405     /**
406      * Set and store the geodata (latitude and longitude) in the output file.
407      * This method should be called before {@link #start}. The geodata is stored
408      * in udta box if the output format is
409      * {@link OutputFormat#MUXER_OUTPUT_MPEG_4}, and is ignored for other output
410      * formats. The geodata is stored according to ISO-6709 standard.
411      *
412      * @param latitude Latitude in degrees. Its value must be in the range [-90,
413      * 90].
414      * @param longitude Longitude in degrees. Its value must be in the range
415      * [-180, 180].
416      * @throws IllegalArgumentException If the given latitude or longitude is out
417      * of range.
418      * @throws IllegalStateException If this method is called after {@link #start}.
419      */
setLocation(float latitude, float longitude)420     public void setLocation(float latitude, float longitude) {
421         int latitudex10000  = (int) (latitude * 10000 + 0.5);
422         int longitudex10000 = (int) (longitude * 10000 + 0.5);
423 
424         if (latitudex10000 > 900000 || latitudex10000 < -900000) {
425             String msg = "Latitude: " + latitude + " out of range.";
426             throw new IllegalArgumentException(msg);
427         }
428         if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
429             String msg = "Longitude: " + longitude + " out of range";
430             throw new IllegalArgumentException(msg);
431         }
432 
433         if (mState == MUXER_STATE_INITIALIZED && mNativeObject != 0) {
434             nativeSetLocation(mNativeObject, latitudex10000, longitudex10000);
435         } else {
436             throw new IllegalStateException("Can't set location due to wrong state.");
437         }
438     }
439 
440     /**
441      * Starts the muxer.
442      * <p>Make sure this is called after {@link #addTrack} and before
443      * {@link #writeSampleData}.</p>
444      * @throws IllegalStateException If this method is called after {@link #start}
445      * or Muxer is released
446      */
start()447     public void start() {
448         if (mNativeObject == 0) {
449             throw new IllegalStateException("Muxer has been released!");
450         }
451         if (mState == MUXER_STATE_INITIALIZED) {
452             nativeStart(mNativeObject);
453             mState = MUXER_STATE_STARTED;
454         } else {
455             throw new IllegalStateException("Can't start due to wrong state.");
456         }
457     }
458 
459     /**
460      * Stops the muxer.
461      * <p>Once the muxer stops, it can not be restarted.</p>
462      * @throws IllegalStateException if muxer is in the wrong state.
463      */
stop()464     public void stop() {
465         if (mState == MUXER_STATE_STARTED) {
466             nativeStop(mNativeObject);
467             mState = MUXER_STATE_STOPPED;
468         } else {
469             throw new IllegalStateException("Can't stop due to wrong state.");
470         }
471     }
472 
473     @Override
finalize()474     protected void finalize() throws Throwable {
475         try {
476             if (mCloseGuard != null) {
477                 mCloseGuard.warnIfOpen();
478             }
479             if (mNativeObject != 0) {
480                 nativeRelease(mNativeObject);
481                 mNativeObject = 0;
482             }
483         } finally {
484             super.finalize();
485         }
486     }
487 
488     /**
489      * Adds a track with the specified format.
490      * <p>
491      * The following table summarizes support for specific format keys across android releases.
492      * Keys marked with '+:' are required.
493      *
494      * <table style="width: 0%">
495      *  <thead>
496      *   <tr>
497      *    <th rowspan=2>OS Version(s)</th>
498      *    <td colspan=3>{@code MediaFormat} keys used for</th>
499      *   </tr><tr>
500      *    <th>All Tracks</th>
501      *    <th>Audio Tracks</th>
502      *    <th>Video Tracks</th>
503      *   </tr>
504      *  </thead>
505      *  <tbody>
506      *   <tr>
507      *    <td>{@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}</td>
508      *    <td rowspan=7>+: {@link MediaFormat#KEY_MIME}</td>
509      *    <td rowspan=3>+: {@link MediaFormat#KEY_SAMPLE_RATE},<br>
510      *        +: {@link MediaFormat#KEY_CHANNEL_COUNT},<br>
511      *        +: <strong>codec-specific data<sup>AAC</sup></strong></td>
512      *    <td rowspan=5>+: {@link MediaFormat#KEY_WIDTH},<br>
513      *        +: {@link MediaFormat#KEY_HEIGHT},<br>
514      *        no {@code KEY_ROTATION},
515      *        use {@link #setOrientationHint setOrientationHint()}<sup>.mp4</sup>,<br>
516      *        +: <strong>codec-specific data<sup>AVC, MPEG4</sup></strong></td>
517      *   </tr><tr>
518      *    <td>{@link android.os.Build.VERSION_CODES#KITKAT}</td>
519      *   </tr><tr>
520      *    <td>{@link android.os.Build.VERSION_CODES#KITKAT_WATCH}</td>
521      *   </tr><tr>
522      *    <td>{@link android.os.Build.VERSION_CODES#LOLLIPOP}</td>
523      *    <td rowspan=4>as above, plus<br>
524      *        +: <strong>codec-specific data<sup>Vorbis & .webm</sup></strong></td>
525      *   </tr><tr>
526      *    <td>{@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}</td>
527      *   </tr><tr>
528      *    <td>{@link android.os.Build.VERSION_CODES#M}</td>
529      *    <td>as above, plus<br>
530      *        {@link MediaFormat#KEY_BIT_RATE}<sup>AAC</sup></td>
531      *   </tr><tr>
532      *    <td>{@link android.os.Build.VERSION_CODES#N}</td>
533      *    <td>as above, plus<br>
534      *        <!-- {link MediaFormat#KEY_MAX_BIT_RATE}<sup>AAC, MPEG4</sup>,<br> -->
535      *        {@link MediaFormat#KEY_BIT_RATE}<sup>MPEG4</sup>,<br>
536      *        {@link MediaFormat#KEY_HDR_STATIC_INFO}<sup>#, .webm</sup>,<br>
537      *        {@link MediaFormat#KEY_COLOR_STANDARD}<sup>#</sup>,<br>
538      *        {@link MediaFormat#KEY_COLOR_TRANSFER}<sup>#</sup>,<br>
539      *        {@link MediaFormat#KEY_COLOR_RANGE}<sup>#</sup>,<br>
540      *        +: <strong>codec-specific data<sup>HEVC</sup></strong>,<br>
541      *        codec-specific data<sup>VP9</sup></td>
542      *   </tr>
543      *   <tr>
544      *    <td colspan=4>
545      *     <p class=note><strong>Notes:</strong><br>
546      *      #: storing into container metadata.<br>
547      *      .mp4, .webm&hellip;: for listed containers<br>
548      *      MPEG4, AAC&hellip;: for listed codecs
549      *    </td>
550      *   </tr><tr>
551      *    <td colspan=4>
552      *     <p class=note>Note that the codec-specific data for the track must be specified using
553      *     this method. Furthermore, codec-specific data must not be passed/specified via the
554      *     {@link #writeSampleData writeSampleData()} call.
555      *    </td>
556      *   </tr>
557      *  </tbody>
558      * </table>
559      *
560      * <p>
561      * The following table summarizes codec support for containers across android releases:
562      *
563      * <table style="width: 0%">
564      *  <thead>
565      *   <tr>
566      *    <th rowspan=2>OS Version(s)</th>
567      *    <td colspan=3>Codec support</th>
568      *   </tr><tr>
569      *    <th>{@linkplain OutputFormat#MUXER_OUTPUT_MPEG_4 MP4}</th>
570      *    <th>{@linkplain OutputFormat#MUXER_OUTPUT_WEBM WEBM}</th>
571      *   </tr>
572      *  </thead>
573      *  <tbody>
574      *   <tr>
575      *    <td>{@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}</td>
576      *    <td rowspan=6>{@link MediaFormat#MIMETYPE_AUDIO_AAC AAC},<br>
577      *        {@link MediaFormat#MIMETYPE_AUDIO_AMR_NB NB-AMR},<br>
578      *        {@link MediaFormat#MIMETYPE_AUDIO_AMR_WB WB-AMR},<br>
579      *        {@link MediaFormat#MIMETYPE_VIDEO_H263 H.263},<br>
580      *        {@link MediaFormat#MIMETYPE_VIDEO_MPEG4 MPEG-4},<br>
581      *        {@link MediaFormat#MIMETYPE_VIDEO_AVC AVC} (H.264)</td>
582      *    <td rowspan=3>Not supported</td>
583      *   </tr><tr>
584      *    <td>{@link android.os.Build.VERSION_CODES#KITKAT}</td>
585      *   </tr><tr>
586      *    <td>{@link android.os.Build.VERSION_CODES#KITKAT_WATCH}</td>
587      *   </tr><tr>
588      *    <td>{@link android.os.Build.VERSION_CODES#LOLLIPOP}</td>
589      *    <td rowspan=3>{@link MediaFormat#MIMETYPE_AUDIO_VORBIS Vorbis},<br>
590      *        {@link MediaFormat#MIMETYPE_VIDEO_VP8 VP8}</td>
591      *   </tr><tr>
592      *    <td>{@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}</td>
593      *   </tr><tr>
594      *    <td>{@link android.os.Build.VERSION_CODES#M}</td>
595      *   </tr><tr>
596      *    <td>{@link android.os.Build.VERSION_CODES#N}</td>
597      *    <td>as above, plus<br>
598      *        {@link MediaFormat#MIMETYPE_VIDEO_HEVC HEVC} (H.265)</td>
599      *    <td>as above, plus<br>
600      *        {@link MediaFormat#MIMETYPE_VIDEO_VP9 VP9}</td>
601      *   </tr>
602      *  </tbody>
603      * </table>
604      *
605      * @param format The media format for the track.  This must not be an empty
606      *               MediaFormat.
607      * @return The track index for this newly added track, and it should be used
608      * in the {@link #writeSampleData}.
609      * @throws IllegalArgumentException if format is invalid.
610      * @throws IllegalStateException if muxer is in the wrong state.
611      */
addTrack(@onNull MediaFormat format)612     public int addTrack(@NonNull MediaFormat format) {
613         if (format == null) {
614             throw new IllegalArgumentException("format must not be null.");
615         }
616         if (mState != MUXER_STATE_INITIALIZED) {
617             throw new IllegalStateException("Muxer is not initialized.");
618         }
619         if (mNativeObject == 0) {
620             throw new IllegalStateException("Muxer has been released!");
621         }
622         int trackIndex = -1;
623         // Convert the MediaFormat into key-value pairs and send to the native.
624         Map<String, Object> formatMap = format.getMap();
625 
626         String[] keys = null;
627         Object[] values = null;
628         int mapSize = formatMap.size();
629         if (mapSize > 0) {
630             keys = new String[mapSize];
631             values = new Object[mapSize];
632             int i = 0;
633             for (Map.Entry<String, Object> entry : formatMap.entrySet()) {
634                 keys[i] = entry.getKey();
635                 values[i] = entry.getValue();
636                 ++i;
637             }
638             trackIndex = nativeAddTrack(mNativeObject, keys, values);
639         } else {
640             throw new IllegalArgumentException("format must not be empty.");
641         }
642 
643         // Track index number is expected to incremented as addTrack succeed.
644         // However, if format is invalid, it will get a negative trackIndex.
645         if (mLastTrackIndex >= trackIndex) {
646             throw new IllegalArgumentException("Invalid format.");
647         }
648         mLastTrackIndex = trackIndex;
649         return trackIndex;
650     }
651 
652     /**
653      * Writes an encoded sample into the muxer.
654      * <p>The application needs to make sure that the samples are written into
655      * the right tracks. Also, it needs to make sure the samples for each track
656      * are written in chronological order (e.g. in the order they are provided
657      * by the encoder.)</p>
658      * @param byteBuf The encoded sample.
659      * @param trackIndex The track index for this sample.
660      * @param bufferInfo The buffer information related to this sample.
661      * @throws IllegalArgumentException if trackIndex, byteBuf or bufferInfo is  invalid.
662      * @throws IllegalStateException if muxer is in wrong state.
663      * MediaMuxer uses the flags provided in {@link MediaCodec.BufferInfo},
664      * to signal sync frames.
665      */
writeSampleData(int trackIndex, @NonNull ByteBuffer byteBuf, @NonNull BufferInfo bufferInfo)666     public void writeSampleData(int trackIndex, @NonNull ByteBuffer byteBuf,
667             @NonNull BufferInfo bufferInfo) {
668         if (trackIndex < 0 || trackIndex > mLastTrackIndex) {
669             throw new IllegalArgumentException("trackIndex is invalid");
670         }
671 
672         if (byteBuf == null) {
673             throw new IllegalArgumentException("byteBuffer must not be null");
674         }
675 
676         if (bufferInfo == null) {
677             throw new IllegalArgumentException("bufferInfo must not be null");
678         }
679         if (bufferInfo.size < 0 || bufferInfo.offset < 0
680                 || (bufferInfo.offset + bufferInfo.size) > byteBuf.capacity()
681                 || bufferInfo.presentationTimeUs < 0) {
682             throw new IllegalArgumentException("bufferInfo must specify a" +
683                     " valid buffer offset, size and presentation time");
684         }
685 
686         if (mNativeObject == 0) {
687             throw new IllegalStateException("Muxer has been released!");
688         }
689 
690         if (mState != MUXER_STATE_STARTED) {
691             throw new IllegalStateException("Can't write, muxer is not started");
692         }
693 
694         nativeWriteSampleData(mNativeObject, trackIndex, byteBuf,
695                 bufferInfo.offset, bufferInfo.size,
696                 bufferInfo.presentationTimeUs, bufferInfo.flags);
697     }
698 
699     /**
700      * Make sure you call this when you're done to free up any resources
701      * instead of relying on the garbage collector to do this for you at
702      * some point in the future.
703      */
release()704     public void release() {
705         if (mState == MUXER_STATE_STARTED) {
706             stop();
707         }
708         if (mNativeObject != 0) {
709             nativeRelease(mNativeObject);
710             mNativeObject = 0;
711             mCloseGuard.close();
712         }
713         mState = MUXER_STATE_UNINITIALIZED;
714     }
715 }
716