This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
MediaMetadataRetriever.java
1407 lines (1326 loc) · 56.7 KB
/
MediaMetadataRetriever.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.media;
import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.FileUtils;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* MediaMetadataRetriever class provides a unified interface for retrieving
* frame and meta data from an input media file.
*/
public class MediaMetadataRetriever implements AutoCloseable {
private static final String TAG = "MediaMetadataRetriever";
// borrowed from ExoPlayer
private static final String[] STANDARD_GENRES = new String[] {
// These are the official ID3v1 genres.
"Blues",
"Classic Rock",
"Country",
"Dance",
"Disco",
"Funk",
"Grunge",
"Hip-Hop",
"Jazz",
"Metal",
"New Age",
"Oldies",
"Other",
"Pop",
"R&B",
"Rap",
"Reggae",
"Rock",
"Techno",
"Industrial",
"Alternative",
"Ska",
"Death Metal",
"Pranks",
"Soundtrack",
"Euro-Techno",
"Ambient",
"Trip-Hop",
"Vocal",
"Jazz+Funk",
"Fusion",
"Trance",
"Classical",
"Instrumental",
"Acid",
"House",
"Game",
"Sound Clip",
"Gospel",
"Noise",
"AlternRock",
"Bass",
"Soul",
"Punk",
"Space",
"Meditative",
"Instrumental Pop",
"Instrumental Rock",
"Ethnic",
"Gothic",
"Darkwave",
"Techno-Industrial",
"Electronic",
"Pop-Folk",
"Eurodance",
"Dream",
"Southern Rock",
"Comedy",
"Cult",
"Gangsta",
"Top 40",
"Christian Rap",
"Pop/Funk",
"Jungle",
"Native American",
"Cabaret",
"New Wave",
"Psychadelic",
"Rave",
"Showtunes",
"Trailer",
"Lo-Fi",
"Tribal",
"Acid Punk",
"Acid Jazz",
"Polka",
"Retro",
"Musical",
"Rock & Roll",
"Hard Rock",
// These were made up by the authors of Winamp and later added to the ID3 spec.
"Folk",
"Folk-Rock",
"National Folk",
"Swing",
"Fast Fusion",
"Bebob",
"Latin",
"Revival",
"Celtic",
"Bluegrass",
"Avantgarde",
"Gothic Rock",
"Progressive Rock",
"Psychedelic Rock",
"Symphonic Rock",
"Slow Rock",
"Big Band",
"Chorus",
"Easy Listening",
"Acoustic",
"Humour",
"Speech",
"Chanson",
"Opera",
"Chamber Music",
"Sonata",
"Symphony",
"Booty Bass",
"Primus",
"Porn Groove",
"Satire",
"Slow Jam",
"Club",
"Tango",
"Samba",
"Folklore",
"Ballad",
"Power Ballad",
"Rhythmic Soul",
"Freestyle",
"Duet",
"Punk Rock",
"Drum Solo",
"A capella",
"Euro-House",
"Dance Hall",
// These were made up by the authors of Winamp but have not been added to the ID3 spec.
"Goa",
"Drum & Bass",
"Club-House",
"Hardcore",
"Terror",
"Indie",
"BritPop",
"Afro-Punk",
"Polsk Punk",
"Beat",
"Christian Gangsta Rap",
"Heavy Metal",
"Black Metal",
"Crossover",
"Contemporary Christian",
"Christian Rock",
"Merengue",
"Salsa",
"Thrash Metal",
"Anime",
"Jpop",
"Synthpop"
};
static {
System.loadLibrary("media_jni");
native_init();
}
// The field below is accessed by native methods
@SuppressWarnings("unused")
private long mNativeContext;
private static final int EMBEDDED_PICTURE_TYPE_ANY = 0xFFFF;
public MediaMetadataRetriever() {
native_setup();
}
/**
* Sets the data source (file pathname) to use. Call this
* method before the rest of the methods in this class. This method may be
* time-consuming.
*
* @param path The path, or the URI (doesn't support streaming source currently)
* of the input media file.
* @throws IllegalArgumentException If the path is invalid.
*/
public void setDataSource(String path) throws IllegalArgumentException {
if (path == null) {
throw new IllegalArgumentException("null path");
}
final Uri uri = Uri.parse(path);
final String scheme = uri.getScheme();
if ("file".equals(scheme)) {
path = uri.getPath();
} else if (scheme != null) {
setDataSource(path, new HashMap<String, String>());
return;
}
try (FileInputStream is = new FileInputStream(path)) {
FileDescriptor fd = is.getFD();
setDataSource(fd, 0, 0x7ffffffffffffffL);
} catch (FileNotFoundException fileEx) {
throw new IllegalArgumentException(path + " does not exist");
} catch (IOException ioEx) {
throw new IllegalArgumentException("couldn't open " + path);
}
}
/**
* Sets the data source (URI) to use. Call this
* method before the rest of the methods in this class. This method may be
* time-consuming.
*
* @param uri The URI of the input media.
* @param headers the headers to be sent together with the request for the data
* @throws IllegalArgumentException If the URI is invalid.
*/
public void setDataSource(String uri, Map<String, String> headers)
throws IllegalArgumentException {
int i = 0;
String[] keys = new String[headers.size()];
String[] values = new String[headers.size()];
for (Map.Entry<String, String> entry: headers.entrySet()) {
keys[i] = entry.getKey();
values[i] = entry.getValue();
++i;
}
_setDataSource(
MediaHTTPService.createHttpServiceBinderIfNecessary(uri),
uri,
keys,
values);
}
private native void _setDataSource(
IBinder httpServiceBinder, String uri, String[] keys, String[] values)
throws IllegalArgumentException;
/**
* Sets the data source (FileDescriptor) to use. It is the caller's
* responsibility to close the file descriptor. It is safe to do so as soon
* as this call returns. Call this method before the rest of the methods in
* this class. This method may be time-consuming.
*
* @param fd the FileDescriptor for the file you want to play
* @param offset the offset into the file where the data to be played starts,
* in bytes. It must be non-negative
* @param length the length in bytes of the data to be played. It must be
* non-negative.
* @throws IllegalArgumentException if the arguments are invalid
*/
public void setDataSource(FileDescriptor fd, long offset, long length)
throws IllegalArgumentException {
try (ParcelFileDescriptor modernFd = FileUtils.convertToModernFd(fd)) {
if (modernFd == null) {
_setDataSource(fd, offset, length);
} else {
_setDataSource(modernFd.getFileDescriptor(), offset, length);
}
} catch (IOException e) {
Log.w(TAG, "Ignoring IO error while setting data source", e);
}
}
private native void _setDataSource(FileDescriptor fd, long offset, long length)
throws IllegalArgumentException;
/**
* Sets the data source (FileDescriptor) to use. It is the caller's
* responsibility to close the file descriptor. It is safe to do so as soon
* as this call returns. Call this method before the rest of the methods in
* this class. This method may be time-consuming.
*
* @param fd the FileDescriptor for the file you want to play
* @throws IllegalArgumentException if the FileDescriptor is invalid
*/
public void setDataSource(FileDescriptor fd)
throws IllegalArgumentException {
// intentionally less than LONG_MAX
setDataSource(fd, 0, 0x7ffffffffffffffL);
}
/**
* Sets the data source as a content Uri. Call this method before
* the rest of the methods in this class. This method may be time-consuming.
*
* @param context the Context to use when resolving the Uri
* @param uri the Content URI of the data you want to play
* @throws IllegalArgumentException if the Uri is invalid
* @throws SecurityException if the Uri cannot be used due to lack of
* permission.
*/
public void setDataSource(Context context, Uri uri)
throws IllegalArgumentException, SecurityException {
if (uri == null) {
throw new IllegalArgumentException("null uri");
}
String scheme = uri.getScheme();
if(scheme == null || scheme.equals("file")) {
setDataSource(uri.getPath());
return;
}
AssetFileDescriptor fd = null;
try {
ContentResolver resolver = context.getContentResolver();
try {
boolean optimize =
SystemProperties.getBoolean("fuse.sys.transcode_retriever_optimize", false);
Bundle opts = new Bundle();
opts.putBoolean("android.provider.extra.ACCEPT_ORIGINAL_MEDIA_FORMAT", true);
fd = optimize ? resolver.openTypedAssetFileDescriptor(uri, "*/*", opts)
: resolver.openAssetFileDescriptor(uri, "r");
} catch(FileNotFoundException e) {
throw new IllegalArgumentException("could not access " + uri);
}
if (fd == null) {
throw new IllegalArgumentException("got null FileDescriptor for " + uri);
}
FileDescriptor descriptor = fd.getFileDescriptor();
if (!descriptor.valid()) {
throw new IllegalArgumentException("got invalid FileDescriptor for " + uri);
}
// Note: using getDeclaredLength so that our behavior is the same
// as previous versions when the content provider is returning
// a full file.
if (fd.getDeclaredLength() < 0) {
setDataSource(descriptor);
} else {
setDataSource(descriptor, fd.getStartOffset(), fd.getDeclaredLength());
}
return;
} catch (SecurityException ex) {
} finally {
try {
if (fd != null) {
fd.close();
}
} catch(IOException ioEx) {
}
}
setDataSource(uri.toString());
}
/**
* Sets the data source (MediaDataSource) to use.
*
* @param dataSource the MediaDataSource for the media you want to play
*/
public void setDataSource(MediaDataSource dataSource)
throws IllegalArgumentException {
_setDataSource(dataSource);
}
private native void _setDataSource(MediaDataSource dataSource)
throws IllegalArgumentException;
private native @Nullable String nativeExtractMetadata(int keyCode);
/**
* Call this method after setDataSource(). This method retrieves the
* meta data value associated with the keyCode.
*
* The keyCode currently supported is listed below as METADATA_XXX
* constants. With any other value, it returns a null pointer.
*
* @param keyCode One of the constants listed below at the end of the class.
* @return The meta data value associate with the given keyCode on success;
* null on failure.
*/
public @Nullable String extractMetadata(int keyCode) {
String meta = nativeExtractMetadata(keyCode);
if (keyCode == METADATA_KEY_GENRE) {
// translate numeric genre code(s) to human readable
meta = convertGenreTag(meta);
}
return meta;
}
/*
* The id3v2 spec doesn't specify the syntax of the genre tag very precisely, so
* some assumptions are made. Using one possible interpretation of the id3v2
* spec, this method converts an id3 genre tag string to a human readable string,
* as follows:
* - if the first character of the tag is a digit, the entire tag is assumed to
* be an id3v1 numeric genre code. If the tag does not parse to a number, or
* the number is outside the range of defined standard genres, it is ignored.
* - if the tag does not start with a digit, it is assumed to be an id3v2 style
* tag consisting of one or more genres, with each genre being either a parenthesized
* integer referring to an id3v1 numeric genre code, the special indicators "(CR)" or
* "(RX)" (for "Cover" or "Remix", respectively), or a custom genre string. When
* a custom genre string is encountered, it is assumed to continue until the end
* of the tag, unless it starts with "((" in which case it is assumed to continue
* until the next close-parenthesis or the end of the tag. Any parse error in the tag
* causes it to be ignored.
* The human-readable genre string is not localized, and uses the English genre names
* from the spec.
*/
private String convertGenreTag(String meta) {
if (TextUtils.isEmpty(meta)) {
return null;
}
if (Character.isDigit(meta.charAt(0))) {
// assume a single id3v1-style bare number without any extra characters
try {
int genreIndex = Integer.parseInt(meta);
if (genreIndex >= 0 && genreIndex < STANDARD_GENRES.length) {
return STANDARD_GENRES[genreIndex];
}
} catch (NumberFormatException e) {
// ignore and fall through
}
return null;
} else {
// assume id3v2-style genre tag, with parenthesized numeric genres
// and/or literal genre strings, possibly more than one per tag.
StringBuilder genres = null;
String nextGenre = null;
while (true) {
if (!TextUtils.isEmpty(nextGenre)) {
if (genres == null) {
genres = new StringBuilder();
}
if (genres.length() != 0) {
genres.append(", ");
}
genres.append(nextGenre);
nextGenre = null;
}
if (TextUtils.isEmpty(meta)) {
// entire tag has been processed.
break;
}
if (meta.startsWith("(RX)")) {
nextGenre = "Remix";
meta = meta.substring(4);
} else if (meta.startsWith("(CR)")) {
nextGenre = "Cover";
meta = meta.substring(4);
} else if (meta.startsWith("((")) {
// the id3v2 spec says that custom genres that start with a parenthesis
// should be "escaped" with another parenthesis, however the spec doesn't
// specify escaping parentheses inside the custom string. We'll parse any
// such strings until a closing parenthesis is found, or the end of
// the tag is reached.
int closeParenOffset = meta.indexOf(')');
if (closeParenOffset == -1) {
// string continues to end of tag
nextGenre = meta.substring(1);
meta = "";
} else {
nextGenre = meta.substring(1, closeParenOffset + 1);
meta = meta.substring(closeParenOffset + 1);
}
} else if (meta.startsWith("(")) {
// should be a parenthesized numeric genre
int closeParenOffset = meta.indexOf(')');
if (closeParenOffset == -1) {
return null;
}
String genreNumString = meta.substring(1, closeParenOffset);
try {
int genreIndex = Integer.parseInt(genreNumString.toString());
if (genreIndex >= 0 && genreIndex < STANDARD_GENRES.length) {
nextGenre = STANDARD_GENRES[genreIndex];
} else {
return null;
}
} catch (NumberFormatException e) {
return null;
}
meta = meta.substring(closeParenOffset + 1);
} else {
// custom genre
nextGenre = meta;
meta = "";
}
}
return genres == null || genres.length() == 0 ? null : genres.toString();
}
}
/**
* This method is similar to {@link #getFrameAtTime(long, int, BitmapParams)}
* except that the device will choose the actual {@link Bitmap.Config} to use.
*
* @param timeUs The time position where the frame will be retrieved.
* When retrieving the frame at the given time position, there is no
* guarantee that the data source has a frame located at the position.
* When this happens, a frame nearby will be returned. If timeUs is
* negative, time position and option will ignored, and any frame
* that the implementation considers as representative may be returned.
*
* @param option a hint on how the frame is found. Use
* {@link #OPTION_PREVIOUS_SYNC} if one wants to retrieve a sync frame
* that has a timestamp earlier than or the same as timeUs. Use
* {@link #OPTION_NEXT_SYNC} if one wants to retrieve a sync frame
* that has a timestamp later than or the same as timeUs. Use
* {@link #OPTION_CLOSEST_SYNC} if one wants to retrieve a sync frame
* that has a timestamp closest to or the same as timeUs. Use
* {@link #OPTION_CLOSEST} if one wants to retrieve a frame that may
* or may not be a sync frame but is closest to or the same as timeUs.
* {@link #OPTION_CLOSEST} often has larger performance overhead compared
* to the other options if there is no sync frame located at timeUs.
*
* @return A Bitmap containing a representative video frame, which can be null,
* if such a frame cannot be retrieved. {@link Bitmap#getConfig()} can
* be used to query the actual {@link Bitmap.Config}.
*
* @see #getFrameAtTime(long, int, BitmapParams)
*/
public @Nullable Bitmap getFrameAtTime(long timeUs, @Option int option) {
if (option < OPTION_PREVIOUS_SYNC ||
option > OPTION_CLOSEST) {
throw new IllegalArgumentException("Unsupported option: " + option);
}
return _getFrameAtTime(timeUs, option, -1 /*dst_width*/, -1 /*dst_height*/, null);
}
/**
* Call this method after setDataSource(). This method finds a
* representative frame close to the given time position by considering
* the given option if possible, and returns it as a bitmap.
*
* <p>If you don't need a full-resolution
* frame (for example, because you need a thumbnail image), use
* {@link #getScaledFrameAtTime getScaledFrameAtTime()} instead of this
* method.</p>
*
* @param timeUs The time position where the frame will be retrieved.
* When retrieving the frame at the given time position, there is no
* guarantee that the data source has a frame located at the position.
* When this happens, a frame nearby will be returned. If timeUs is
* negative, time position and option will ignored, and any frame
* that the implementation considers as representative may be returned.
*
* @param option a hint on how the frame is found. Use
* {@link #OPTION_PREVIOUS_SYNC} if one wants to retrieve a sync frame
* that has a timestamp earlier than or the same as timeUs. Use
* {@link #OPTION_NEXT_SYNC} if one wants to retrieve a sync frame
* that has a timestamp later than or the same as timeUs. Use
* {@link #OPTION_CLOSEST_SYNC} if one wants to retrieve a sync frame
* that has a timestamp closest to or the same as timeUs. Use
* {@link #OPTION_CLOSEST} if one wants to retrieve a frame that may
* or may not be a sync frame but is closest to or the same as timeUs.
* {@link #OPTION_CLOSEST} often has larger performance overhead compared
* to the other options if there is no sync frame located at timeUs.
*
* @param params BitmapParams that controls the returned bitmap config
* (such as pixel formats).
*
* @return A Bitmap containing a representative video frame, which
* can be null, if such a frame cannot be retrieved.
*
* @see #getFrameAtTime(long, int)
*/
public @Nullable Bitmap getFrameAtTime(
long timeUs, @Option int option, @NonNull BitmapParams params) {
if (option < OPTION_PREVIOUS_SYNC ||
option > OPTION_CLOSEST) {
throw new IllegalArgumentException("Unsupported option: " + option);
}
return _getFrameAtTime(timeUs, option, -1 /*dst_width*/, -1 /*dst_height*/, params);
}
/**
* This method is similar to {@link #getScaledFrameAtTime(long, int, int, int, BitmapParams)}
* except that the device will choose the actual {@link Bitmap.Config} to use.
*
* @param timeUs The time position in microseconds where the frame will be retrieved.
* When retrieving the frame at the given time position, there is no
* guarantee that the data source has a frame located at the position.
* When this happens, a frame nearby will be returned. If timeUs is
* negative, time position and option will ignored, and any frame
* that the implementation considers as representative may be returned.
*
* @param option a hint on how the frame is found. Use
* {@link #OPTION_PREVIOUS_SYNC} if one wants to retrieve a sync frame
* that has a timestamp earlier than or the same as timeUs. Use
* {@link #OPTION_NEXT_SYNC} if one wants to retrieve a sync frame
* that has a timestamp later than or the same as timeUs. Use
* {@link #OPTION_CLOSEST_SYNC} if one wants to retrieve a sync frame
* that has a timestamp closest to or the same as timeUs. Use
* {@link #OPTION_CLOSEST} if one wants to retrieve a frame that may
* or may not be a sync frame but is closest to or the same as timeUs.
* {@link #OPTION_CLOSEST} often has larger performance overhead compared
* to the other options if there is no sync frame located at timeUs.
*
* @param dstWidth expected output bitmap width
* @param dstHeight expected output bitmap height
* @return A Bitmap containing a representative video frame, which can be null,
* if such a frame cannot be retrieved. {@link Bitmap#getConfig()} can
* be used to query the actual {@link Bitmap.Config}.
* @throws IllegalArgumentException if passed in invalid option or width by height
* is less than or equal to 0.
* @see #getScaledFrameAtTime(long, int, int, int, BitmapParams)
*/
public @Nullable Bitmap getScaledFrameAtTime(long timeUs, @Option int option,
@IntRange(from=1) int dstWidth, @IntRange(from=1) int dstHeight) {
validate(option, dstWidth, dstHeight);
return _getFrameAtTime(timeUs, option, dstWidth, dstHeight, null);
}
/**
* Retrieve a video frame near a given timestamp scaled to a desired size.
* Call this method after setDataSource(). This method finds a representative
* frame close to the given time position by considering the given option
* if possible, and returns it as a bitmap with same aspect ratio as the source
* while scaling it so that it fits into the desired size of dst_width by dst_height.
* This is useful for generating a thumbnail for an input data source or just to
* obtain a scaled frame at the given time position.
*
* @param timeUs The time position in microseconds where the frame will be retrieved.
* When retrieving the frame at the given time position, there is no
* guarantee that the data source has a frame located at the position.
* When this happens, a frame nearby will be returned. If timeUs is
* negative, time position and option will ignored, and any frame
* that the implementation considers as representative may be returned.
*
* @param option a hint on how the frame is found. Use
* {@link #OPTION_PREVIOUS_SYNC} if one wants to retrieve a sync frame
* that has a timestamp earlier than or the same as timeUs. Use
* {@link #OPTION_NEXT_SYNC} if one wants to retrieve a sync frame
* that has a timestamp later than or the same as timeUs. Use
* {@link #OPTION_CLOSEST_SYNC} if one wants to retrieve a sync frame
* that has a timestamp closest to or the same as timeUs. Use
* {@link #OPTION_CLOSEST} if one wants to retrieve a frame that may
* or may not be a sync frame but is closest to or the same as timeUs.
* {@link #OPTION_CLOSEST} often has larger performance overhead compared
* to the other options if there is no sync frame located at timeUs.
*
* @param dstWidth expected output bitmap width
* @param dstHeight expected output bitmap height
* @param params BitmapParams that controls the returned bitmap config
* (such as pixel formats).
*
* @return A Bitmap of size not larger than dstWidth by dstHeight containing a
* scaled video frame, which can be null, if such a frame cannot be retrieved.
* @throws IllegalArgumentException if passed in invalid option or width by height
* is less than or equal to 0.
* @see #getScaledFrameAtTime(long, int, int, int)
*/
public @Nullable Bitmap getScaledFrameAtTime(long timeUs, @Option int option,
@IntRange(from=1) int dstWidth, @IntRange(from=1) int dstHeight,
@NonNull BitmapParams params) {
validate(option, dstWidth, dstHeight);
return _getFrameAtTime(timeUs, option, dstWidth, dstHeight, params);
}
private void validate(@Option int option, int dstWidth, int dstHeight) {
if (option < OPTION_PREVIOUS_SYNC || option > OPTION_CLOSEST) {
throw new IllegalArgumentException("Unsupported option: " + option);
}
if (dstWidth <= 0) {
throw new IllegalArgumentException("Invalid width: " + dstWidth);
}
if (dstHeight <= 0) {
throw new IllegalArgumentException("Invalid height: " + dstHeight);
}
}
/**
* Call this method after setDataSource(). This method finds a
* representative frame close to the given time position if possible,
* and returns it as a bitmap. Call this method if one does not care
* how the frame is found as long as it is close to the given time;
* otherwise, please call {@link #getFrameAtTime(long, int)}.
*
* <p>If you don't need a full-resolution
* frame (for example, because you need a thumbnail image), use
* {@link #getScaledFrameAtTime getScaledFrameAtTime()} instead of this
* method.</p>
*
* @param timeUs The time position where the frame will be retrieved.
* When retrieving the frame at the given time position, there is no
* guarentee that the data source has a frame located at the position.
* When this happens, a frame nearby will be returned. If timeUs is
* negative, time position and option will ignored, and any frame
* that the implementation considers as representative may be returned.
*
* @return A Bitmap of size dst_widthxdst_height containing a representative
* video frame, which can be null, if such a frame cannot be retrieved.
*
* @see #getFrameAtTime(long, int)
*/
public @Nullable Bitmap getFrameAtTime(long timeUs) {
return getFrameAtTime(timeUs, OPTION_CLOSEST_SYNC);
}
/**
* Call this method after setDataSource(). This method finds a
* representative frame at any time position if possible,
* and returns it as a bitmap. Call this method if one does not
* care about where the frame is located; otherwise, please call
* {@link #getFrameAtTime(long)} or {@link #getFrameAtTime(long, int)}
*
* <p>If you don't need a full-resolution
* frame (for example, because you need a thumbnail image), use
* {@link #getScaledFrameAtTime getScaledFrameAtTime()} instead of this
* method.</p>
*
* @return A Bitmap containing a representative video frame, which
* can be null, if such a frame cannot be retrieved.
*
* @see #getFrameAtTime(long)
* @see #getFrameAtTime(long, int)
*/
public @Nullable Bitmap getFrameAtTime() {
return _getFrameAtTime(
-1, OPTION_CLOSEST_SYNC, -1 /*dst_width*/, -1 /*dst_height*/, null);
}
private native Bitmap _getFrameAtTime(
long timeUs, int option, int width, int height, @Nullable BitmapParams params);
public static final class BitmapParams {
private Bitmap.Config inPreferredConfig = Bitmap.Config.ARGB_8888;
private Bitmap.Config outActualConfig = Bitmap.Config.ARGB_8888;
/**
* Create a default BitmapParams object. By default, it uses {@link Bitmap.Config#ARGB_8888}
* as the preferred bitmap config.
*/
public BitmapParams() {}
/**
* Set the preferred bitmap config for the decoder to decode into.
*
* If not set, or the request cannot be met, the decoder will output
* in {@link Bitmap.Config#ARGB_8888} config by default.
*
* After decode, the actual config used can be retrieved by {@link #getActualConfig()}.
*
* @param config the preferred bitmap config to use.
*/
public void setPreferredConfig(@NonNull Bitmap.Config config) {
if (config == null) {
throw new IllegalArgumentException("preferred config can't be null");
}
inPreferredConfig = config;
}
/**
* Retrieve the preferred bitmap config in the params.
*
* @return the preferred bitmap config.
*/
public @NonNull Bitmap.Config getPreferredConfig() {
return inPreferredConfig;
}
/**
* Get the actual bitmap config used to decode the bitmap after the decoding.
*
* @return the actual bitmap config used.
*/
public @NonNull Bitmap.Config getActualConfig() {
return outActualConfig;
}
}
/**
* This method retrieves a video frame by its index. It should only be called
* after {@link #setDataSource}.
*
* After the bitmap is returned, you can query the actual parameters that were
* used to create the bitmap from the {@code BitmapParams} argument, for instance
* to query the bitmap config used for the bitmap with {@link BitmapParams#getActualConfig}.
*
* @param frameIndex 0-based index of the video frame. The frame index must be that of
* a valid frame. The total number of frames available for retrieval can be queried
* via the {@link #METADATA_KEY_VIDEO_FRAME_COUNT} key.
* @param params BitmapParams that controls the returned bitmap config (such as pixel formats).
*
* @throws IllegalStateException if the container doesn't contain video or image sequences.
* @throws IllegalArgumentException if the requested frame index does not exist.
*
* @return A Bitmap containing the requested video frame, or null if the retrieval fails.
*
* @see #getFrameAtIndex(int)
* @see #getFramesAtIndex(int, int, BitmapParams)
* @see #getFramesAtIndex(int, int)
*/
public @Nullable Bitmap getFrameAtIndex(int frameIndex, @NonNull BitmapParams params) {
List<Bitmap> bitmaps = getFramesAtIndex(frameIndex, 1, params);
return bitmaps.get(0);
}
/**
* This method is similar to {@link #getFrameAtIndex(int, BitmapParams)} except that
* the default for {@link BitmapParams} will be used.
*
* @param frameIndex 0-based index of the video frame. The frame index must be that of
* a valid frame. The total number of frames available for retrieval can be queried
* via the {@link #METADATA_KEY_VIDEO_FRAME_COUNT} key.
*
* @throws IllegalStateException if the container doesn't contain video or image sequences.
* @throws IllegalArgumentException if the requested frame index does not exist.
*
* @return A Bitmap containing the requested video frame, or null if the retrieval fails.
*
* @see #getFrameAtIndex(int, BitmapParams)
* @see #getFramesAtIndex(int, int, BitmapParams)
* @see #getFramesAtIndex(int, int)
*/
public @Nullable Bitmap getFrameAtIndex(int frameIndex) {
List<Bitmap> bitmaps = getFramesAtIndex(frameIndex, 1);
return bitmaps.get(0);
}
/**
* This method retrieves a consecutive set of video frames starting at the
* specified index. It should only be called after {@link #setDataSource}.
*
* If the caller intends to retrieve more than one consecutive video frames,
* this method is preferred over {@link #getFrameAtIndex(int, BitmapParams)} for efficiency.
*
* After the bitmaps are returned, you can query the actual parameters that were
* used to create the bitmaps from the {@code BitmapParams} argument, for instance
* to query the bitmap config used for the bitmaps with {@link BitmapParams#getActualConfig}.
*
* @param frameIndex 0-based index of the first video frame to retrieve. The frame index
* must be that of a valid frame. The total number of frames available for retrieval
* can be queried via the {@link #METADATA_KEY_VIDEO_FRAME_COUNT} key.
* @param numFrames number of consecutive video frames to retrieve. Must be a positive
* value. The stream must contain at least numFrames frames starting at frameIndex.
* @param params BitmapParams that controls the returned bitmap config (such as pixel formats).
*
* @throws IllegalStateException if the container doesn't contain video or image sequences.
* @throws IllegalArgumentException if the frameIndex or numFrames is invalid, or the
* stream doesn't contain at least numFrames starting at frameIndex.
* @return An list of Bitmaps containing the requested video frames. The returned
* array could contain less frames than requested if the retrieval fails.
*
* @see #getFrameAtIndex(int, BitmapParams)
* @see #getFrameAtIndex(int)
* @see #getFramesAtIndex(int, int)
*/
public @NonNull List<Bitmap> getFramesAtIndex(
int frameIndex, int numFrames, @NonNull BitmapParams params) {
return getFramesAtIndexInternal(frameIndex, numFrames, params);
}
/**
* This method is similar to {@link #getFramesAtIndex(int, int, BitmapParams)} except that
* the default for {@link BitmapParams} will be used.
*
* @param frameIndex 0-based index of the first video frame to retrieve. The frame index
* must be that of a valid frame. The total number of frames available for retrieval
* can be queried via the {@link #METADATA_KEY_VIDEO_FRAME_COUNT} key.
* @param numFrames number of consecutive video frames to retrieve. Must be a positive
* value. The stream must contain at least numFrames frames starting at frameIndex.
*
* @throws IllegalStateException if the container doesn't contain video or image sequences.
* @throws IllegalArgumentException if the frameIndex or numFrames is invalid, or the
* stream doesn't contain at least numFrames starting at frameIndex.
* @return An list of Bitmaps containing the requested video frames. The returned
* array could contain less frames than requested if the retrieval fails.
*
* @see #getFrameAtIndex(int, BitmapParams)
* @see #getFrameAtIndex(int)
* @see #getFramesAtIndex(int, int, BitmapParams)
*/
public @NonNull List<Bitmap> getFramesAtIndex(int frameIndex, int numFrames) {
return getFramesAtIndexInternal(frameIndex, numFrames, null);
}
private @NonNull List<Bitmap> getFramesAtIndexInternal(
int frameIndex, int numFrames, @Nullable BitmapParams params) {
if (!"yes".equals(extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO))) {
throw new IllegalStateException("Does not contain video or image sequences");
}
int frameCount = Integer.parseInt(
extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT));
if (frameIndex < 0 || numFrames < 1
|| frameIndex >= frameCount
|| frameIndex > frameCount - numFrames) {
throw new IllegalArgumentException("Invalid frameIndex or numFrames: "
+ frameIndex + ", " + numFrames);
}
return _getFrameAtIndex(frameIndex, numFrames, params);
}
private native @NonNull List<Bitmap> _getFrameAtIndex(
int frameIndex, int numFrames, @Nullable BitmapParams params);
/**
* This method retrieves a still image by its index. It should only be called
* after {@link #setDataSource}.
*
* After the bitmap is returned, you can query the actual parameters that were
* used to create the bitmap from the {@code BitmapParams} argument, for instance
* to query the bitmap config used for the bitmap with {@link BitmapParams#getActualConfig}.
*
* @param imageIndex 0-based index of the image.
* @param params BitmapParams that controls the returned bitmap config (such as pixel formats).
*
* @throws IllegalStateException if the container doesn't contain still images.
* @throws IllegalArgumentException if the requested image does not exist.
*
* @return the requested still image, or null if the image cannot be retrieved.
*
* @see #getImageAtIndex(int)
* @see #getPrimaryImage(BitmapParams)
* @see #getPrimaryImage()
*/
public @Nullable Bitmap getImageAtIndex(int imageIndex, @NonNull BitmapParams params) {
return getImageAtIndexInternal(imageIndex, params);
}
/**
* @hide
*
* This method retrieves the thumbnail image for a still image if it's available.
* It should only be called after {@link #setDataSource}.
*
* @param imageIndex 0-based index of the image, negative value indicates primary image.
* @param params BitmapParams that controls the returned bitmap config (such as pixel formats).
* @param targetSize intended size of one edge (wdith or height) of the thumbnail,
* this is a heuristic for the framework to decide whether the embedded
* thumbnail should be used.
* @param maxPixels maximum pixels of thumbnail, this is a heuristic for the frameowrk to
* decide whehther the embedded thumnbail (or a downscaled version of it)
* should be used.
* @return the retrieved thumbnail, or null if no suitable thumbnail is available.
*/
public native @Nullable Bitmap getThumbnailImageAtIndex(
int imageIndex, @NonNull BitmapParams params, int targetSize, int maxPixels);
/**
* This method is similar to {@link #getImageAtIndex(int, BitmapParams)} except that
* the default for {@link BitmapParams} will be used.
*
* @param imageIndex 0-based index of the image.
*
* @throws IllegalStateException if the container doesn't contain still images.
* @throws IllegalArgumentException if the requested image does not exist.
*
* @return the requested still image, or null if the image cannot be retrieved.
*