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