This repository has been archived by the owner on Sep 29, 2022. It is now read-only.
forked from arthenica/ffmpeg-kit
-
Notifications
You must be signed in to change notification settings - Fork 6
/
FFmpegKitConfig.java
1218 lines (1068 loc) · 46.3 KB
/
FFmpegKitConfig.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) 2018-2021 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract;
import android.util.SparseArray;
import com.arthenica.smartexception.java.Exceptions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
/**
* <p>Configuration class of <code>FFmpegKit</code> library.
*/
public class FFmpegKitConfig {
/**
* The tag used for logging.
*/
static final String TAG = "ffmpeg-kit";
/**
* Prefix of named pipes created by ffmpeg kit.
*/
static final String FFMPEG_KIT_NAMED_PIPE_PREFIX = "fk_pipe_";
/**
* Generates ids for named ffmpeg kit pipes.
*/
private static final AtomicLong pipeIndexGenerator;
private static Level activeLogLevel;
/* Session history variables */
private static int sessionHistorySize;
private static final Map<Long, Session> sessionHistoryMap;
private static final List<Session> sessionHistoryList;
private static final Object sessionHistoryLock;
private static int asyncConcurrencyLimit;
private static ExecutorService asyncExecutorService;
/* Global callbacks */
private static LogCallback globalLogCallbackFunction;
private static StatisticsCallback globalStatisticsCallbackFunction;
private static ExecuteCallback globalExecuteCallbackFunction;
private static final SparseArray<ParcelFileDescriptor> pfdMap;
private static LogRedirectionStrategy globalLogRedirectionStrategy;
static {
Exceptions.registerRootPackage("com.arthenica");
android.util.Log.i(FFmpegKitConfig.TAG, "Loading ffmpeg-kit.");
final boolean nativeFFmpegTriedAndFailed = NativeLoader.loadFFmpeg();
/* ALL FFMPEG-KIT LIBRARIES LOADED AT STARTUP */
Abi.class.getName();
FFmpegKit.class.getName();
FFprobeKit.class.getName();
NativeLoader.loadFFmpegKit(nativeFFmpegTriedAndFailed);
android.util.Log.i(FFmpegKitConfig.TAG, String.format("Loaded ffmpeg-kit-%s-%s-%s-%s.", NativeLoader.loadPackageName(), NativeLoader.loadAbi(), NativeLoader.loadVersion(), NativeLoader.loadBuildDate()));
pipeIndexGenerator = new AtomicLong(1);
/* NATIVE LOG LEVEL IS RECEIVED ONLY ON STARTUP */
activeLogLevel = Level.from(NativeLoader.loadLogLevel());
asyncConcurrencyLimit = 10;
asyncExecutorService = Executors.newFixedThreadPool(asyncConcurrencyLimit);
sessionHistorySize = 10;
sessionHistoryMap = new LinkedHashMap<Long, Session>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Long, Session> eldest) {
return (this.size() > sessionHistorySize);
}
};
sessionHistoryList = new LinkedList<>();
sessionHistoryLock = new Object();
globalLogCallbackFunction = null;
globalStatisticsCallbackFunction = null;
globalExecuteCallbackFunction = null;
pfdMap = new SparseArray<>();
globalLogRedirectionStrategy = LogRedirectionStrategy.PRINT_LOGS_WHEN_NO_CALLBACKS_DEFINED;
NativeLoader.enableRedirection();
}
/**
* Default constructor hidden.
*/
private FFmpegKitConfig() {
}
/**
* <p>Enables log and statistics redirection.
*
* <p>When redirection is enabled FFmpeg/FFprobe logs are redirected to Logcat and sessions
* collect log and statistics entries for the executions. It is possible to define global or
* session specific log/statistics callbacks as well.
*
* <p>Note that redirection is enabled by default. If you do not want to use its functionality
* please use {@link #disableRedirection()} to disable it.
*/
public static void enableRedirection() {
enableNativeRedirection();
}
/**
* <p>Disables log and statistics redirection.
*
* <p>When redirection is disabled logs are printed to stderr, all logs and statistics
* callbacks are disabled and <code>FFprobe</code>'s <code>getMediaInformation</code> methods
* do not work.
*/
public static void disableRedirection() {
disableNativeRedirection();
}
/**
* <p>Log redirection method called by the native library.
*
* @param sessionId id of the session that generated this log, 0 for logs that do not belong
* to a specific session
* @param levelValue log level as defined in {@link Level}
* @param logMessage redirected log message data
*/
private static void log(final long sessionId, final int levelValue, final byte[] logMessage) {
final Level level = Level.from(levelValue);
final String text = new String(logMessage);
final Log log = new Log(sessionId, level, text);
boolean globalCallbackDefined = false;
boolean sessionCallbackDefined = false;
LogRedirectionStrategy activeLogRedirectionStrategy = globalLogRedirectionStrategy;
// AV_LOG_STDERR logs are always redirected
if ((activeLogLevel == Level.AV_LOG_QUIET && levelValue != Level.AV_LOG_STDERR.getValue()) || levelValue > activeLogLevel.getValue()) {
// LOG NEITHER PRINTED NOR FORWARDED
return;
}
final Session session = getSession(sessionId);
if (session != null) {
activeLogRedirectionStrategy = session.getLogRedirectionStrategy();
session.addLog(log);
if (session.getLogCallback() != null) {
sessionCallbackDefined = true;
try {
// NOTIFY SESSION CALLBACK DEFINED
session.getLogCallback().apply(log);
} catch (final Exception e) {
android.util.Log.e(FFmpegKitConfig.TAG, String.format("Exception thrown inside session LogCallback block.%s", Exceptions.getStackTraceString(e)));
}
}
}
final LogCallback globalLogCallbackFunction = FFmpegKitConfig.globalLogCallbackFunction;
if (globalLogCallbackFunction != null) {
globalCallbackDefined = true;
try {
// NOTIFY GLOBAL CALLBACK DEFINED
globalLogCallbackFunction.apply(log);
} catch (final Exception e) {
android.util.Log.e(FFmpegKitConfig.TAG, String.format("Exception thrown inside global LogCallback block.%s", Exceptions.getStackTraceString(e)));
}
}
// EXECUTE THE LOG STRATEGY
switch (activeLogRedirectionStrategy) {
case NEVER_PRINT_LOGS: {
return;
}
case PRINT_LOGS_WHEN_GLOBAL_CALLBACK_NOT_DEFINED: {
if (globalCallbackDefined) {
return;
}
}
break;
case PRINT_LOGS_WHEN_SESSION_CALLBACK_NOT_DEFINED: {
if (sessionCallbackDefined) {
return;
}
}
case PRINT_LOGS_WHEN_NO_CALLBACKS_DEFINED: {
if (globalCallbackDefined || sessionCallbackDefined) {
return;
}
}
case ALWAYS_PRINT_LOGS: {
}
}
// PRINT LOGS
switch (level) {
case AV_LOG_QUIET: {
// PRINT NO OUTPUT
}
break;
case AV_LOG_TRACE:
case AV_LOG_DEBUG: {
android.util.Log.d(TAG, text);
}
break;
case AV_LOG_INFO: {
android.util.Log.i(TAG, text);
}
break;
case AV_LOG_WARNING: {
android.util.Log.w(TAG, text);
}
break;
case AV_LOG_ERROR:
case AV_LOG_FATAL:
case AV_LOG_PANIC: {
android.util.Log.e(TAG, text);
}
break;
case AV_LOG_STDERR:
case AV_LOG_VERBOSE:
default: {
android.util.Log.v(TAG, text);
}
break;
}
}
/**
* <p>Statistics redirection method called by the native library.
*
* @param sessionId id of the session that generated this statistics, 0 by default
* @param videoFrameNumber frame number for videos
* @param videoFps frames per second value for videos
* @param videoQuality quality of the video stream
* @param size size in bytes
* @param time processed duration in milliseconds
* @param bitrate output bit rate in kbits/s
* @param speed processing speed = processed duration / operation duration
*/
private static void statistics(final long sessionId, final int videoFrameNumber,
final float videoFps, final float videoQuality, final long size,
final int time, final double bitrate, final double speed) {
final Statistics statistics = new Statistics(sessionId, videoFrameNumber, videoFps, videoQuality, size, time, bitrate, speed);
final Session session = getSession(sessionId);
if (session != null && session.isFFmpeg()) {
FFmpegSession ffmpegSession = (FFmpegSession) session;
ffmpegSession.addStatistics(statistics);
if (ffmpegSession.getStatisticsCallback() != null) {
try {
// NOTIFY SESSION CALLBACK IF DEFINED
ffmpegSession.getStatisticsCallback().apply(statistics);
} catch (final Exception e) {
android.util.Log.e(FFmpegKitConfig.TAG, String.format("Exception thrown inside session StatisticsCallback block.%s", Exceptions.getStackTraceString(e)));
}
}
}
final StatisticsCallback globalStatisticsCallbackFunction = FFmpegKitConfig.globalStatisticsCallbackFunction;
if (globalStatisticsCallbackFunction != null) {
try {
// NOTIFY GLOBAL CALLBACK IF DEFINED
globalStatisticsCallbackFunction.apply(statistics);
} catch (final Exception e) {
android.util.Log.e(FFmpegKitConfig.TAG, String.format("Exception thrown inside global StatisticsCallback block.%s", Exceptions.getStackTraceString(e)));
}
}
}
/**
* <p>Sets and overrides <code>fontconfig</code> configuration directory.
*
* @param path directory that contains fontconfig configuration (fonts.conf)
* @return zero on success, non-zero on error
*/
public static int setFontconfigConfigurationPath(final String path) {
return setNativeEnvironmentVariable("FONTCONFIG_PATH", path);
}
/**
* <p>Registers the fonts inside the given path, so they become available to use in FFmpeg
* filters.
*
* <p>Note that you need to build <code>FFmpegKit</code> with <code>fontconfig</code>
* enabled or use a prebuilt package with <code>fontconfig</code> inside to be able to use
* fonts in <code>FFmpeg</code>.
*
* @param context application context to access application data
* @param fontDirectoryPath directory that contains fonts (.ttf and .otf files)
* @param fontNameMapping custom font name mappings, useful to access your fonts with more
* friendly names
*/
public static void setFontDirectory(final Context context, final String fontDirectoryPath, final Map<String, String> fontNameMapping) {
setFontDirectoryList(context, Collections.singletonList(fontDirectoryPath), fontNameMapping);
}
/**
* <p>Registers the fonts inside the given list of font directories, so they become available
* to use in FFmpeg filters.
*
* <p>Note that you need to build <code>FFmpegKit</code> with <code>fontconfig</code>
* enabled or use a prebuilt package with <code>fontconfig</code> inside to be able to use
* fonts in <code>FFmpeg</code>.
*
* @param context application context to access application data
* @param fontDirectoryList list of directories that contain fonts (.ttf and .otf files)
* @param fontNameMapping custom font name mappings, useful to access your fonts with more
* friendly names
*/
public static void setFontDirectoryList(final Context context, final List<String> fontDirectoryList, final Map<String, String> fontNameMapping) {
final File cacheDir = context.getCacheDir();
int validFontNameMappingCount = 0;
final File tempConfigurationDirectory = new File(cacheDir, "fontconfig");
if (!tempConfigurationDirectory.exists()) {
boolean tempFontConfDirectoryCreated = tempConfigurationDirectory.mkdirs();
android.util.Log.d(TAG, String.format("Created temporary font conf directory: %s.", tempFontConfDirectoryCreated));
}
final File fontConfiguration = new File(tempConfigurationDirectory, "fonts.conf");
if (fontConfiguration.exists()) {
boolean fontConfigurationDeleted = fontConfiguration.delete();
android.util.Log.d(TAG, String.format("Deleted old temporary font configuration: %s.", fontConfigurationDeleted));
}
/* PROCESS MAPPINGS FIRST */
final StringBuilder fontNameMappingBlock = new StringBuilder("");
if (fontNameMapping != null && (fontNameMapping.size() > 0)) {
fontNameMapping.entrySet();
for (Map.Entry<String, String> mapping : fontNameMapping.entrySet()) {
String fontName = mapping.getKey();
String mappedFontName = mapping.getValue();
if ((fontName != null) && (mappedFontName != null) && (fontName.trim().length() > 0) && (mappedFontName.trim().length() > 0)) {
fontNameMappingBlock.append(" <match target=\"pattern\">\n");
fontNameMappingBlock.append(" <test qual=\"any\" name=\"family\">\n");
fontNameMappingBlock.append(String.format(" <string>%s</string>\n", fontName));
fontNameMappingBlock.append(" </test>\n");
fontNameMappingBlock.append(" <edit name=\"family\" mode=\"assign\" binding=\"same\">\n");
fontNameMappingBlock.append(String.format(" <string>%s</string>\n", mappedFontName));
fontNameMappingBlock.append(" </edit>\n");
fontNameMappingBlock.append(" </match>\n");
validFontNameMappingCount++;
}
}
}
final StringBuilder fontConfigBuilder = new StringBuilder();
fontConfigBuilder.append("<?xml version=\"1.0\"?>\n");
fontConfigBuilder.append("<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n");
fontConfigBuilder.append("<fontconfig>\n");
fontConfigBuilder.append(" <dir prefix=\"cwd\">.</dir>\n");
for (String fontDirectoryPath : fontDirectoryList) {
fontConfigBuilder.append(" <dir>");
fontConfigBuilder.append(fontDirectoryPath);
fontConfigBuilder.append("</dir>\n");
}
fontConfigBuilder.append(fontNameMappingBlock);
fontConfigBuilder.append("</fontconfig>");
final AtomicReference<FileOutputStream> reference = new AtomicReference<>();
try {
final FileOutputStream outputStream = new FileOutputStream(fontConfiguration);
reference.set(outputStream);
outputStream.write(fontConfigBuilder.toString().getBytes());
outputStream.flush();
android.util.Log.d(TAG, String.format("Saved new temporary font configuration with %d font name mappings.", validFontNameMappingCount));
setFontconfigConfigurationPath(tempConfigurationDirectory.getAbsolutePath());
for (String fontDirectoryPath : fontDirectoryList) {
android.util.Log.d(TAG, String.format("Font directory %s registered successfully.", fontDirectoryPath));
}
} catch (final IOException e) {
android.util.Log.e(TAG, String.format("Failed to set font directory: %s.%s", Arrays.toString(fontDirectoryList.toArray()), Exceptions.getStackTraceString(e)));
} finally {
if (reference.get() != null) {
try {
reference.get().close();
} catch (IOException e) {
// DO NOT PRINT THIS ERROR
}
}
}
}
/**
* <p>Creates a new named pipe to use in <code>FFmpeg</code> operations.
*
* <p>Please note that creator is responsible of closing created pipes.
*
* @param context application context
* @return the full path of the named pipe
*/
public static String registerNewFFmpegPipe(final Context context) {
// PIPES ARE CREATED UNDER THE PIPES DIRECTORY
final File cacheDir = context.getCacheDir();
final File pipesDir = new File(cacheDir, "pipes");
if (!pipesDir.exists()) {
final boolean pipesDirCreated = pipesDir.mkdirs();
if (!pipesDirCreated) {
android.util.Log.e(TAG, String.format("Failed to create pipes directory: %s.", pipesDir.getAbsolutePath()));
return null;
}
}
final String newFFmpegPipePath = MessageFormat.format("{0}{1}{2}{3}", pipesDir, File.separator, FFMPEG_KIT_NAMED_PIPE_PREFIX, pipeIndexGenerator.getAndIncrement());
// FIRST CLOSE OLD PIPES WITH THE SAME NAME
closeFFmpegPipe(newFFmpegPipePath);
int rc = registerNewNativeFFmpegPipe(newFFmpegPipePath);
if (rc == 0) {
return newFFmpegPipePath;
} else {
android.util.Log.e(TAG, String.format("Failed to register new FFmpeg pipe %s. Operation failed with rc=%d.", newFFmpegPipePath, rc));
return null;
}
}
/**
* <p>Closes a previously created <code>FFmpeg</code> pipe.
*
* @param ffmpegPipePath full path of the FFmpeg pipe
*/
public static void closeFFmpegPipe(final String ffmpegPipePath) {
final File file = new File(ffmpegPipePath);
if (file.exists()) {
file.delete();
}
}
/**
* Returns the list of camera ids supported. These devices can be used in <code>FFmpeg</code>
* commands.
*
* <p>Note that this method requires API Level ≥ 24. On older API levels it returns an empty
* list.
*
* @param context application context
* @return list of camera ids supported or an empty list if no supported cameras are found
*/
public static List<String> getSupportedCameraIds(final Context context) {
final List<String> detectedCameraIdList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
detectedCameraIdList.addAll(CameraSupport.extractSupportedCameraIds(context));
}
return detectedCameraIdList;
}
/**
* <p>Returns the version of FFmpeg bundled within <code>FFmpegKit</code> library.
*
* @return the version of FFmpeg
*/
public static String getFFmpegVersion() {
return getNativeFFmpegVersion();
}
/**
* <p>Returns FFmpegKit library version.
*
* @return FFmpegKit version
*/
public static String getVersion() {
if (isLTSBuild()) {
return String.format("%s-lts", getNativeVersion());
} else {
return getNativeVersion();
}
}
/**
* <p>Returns whether FFmpegKit release is a Long Term Release or not.
*
* @return true/yes or false/no
*/
public static boolean isLTSBuild() {
return AbiDetect.isNativeLTSBuild();
}
/**
* <p>Returns FFmpegKit library build date.
*
* @return FFmpegKit library build date
*/
public static String getBuildDate() {
return getNativeBuildDate();
}
/**
* <p>Prints the given string to Logcat using the given priority. If string provided is bigger
* than the Logcat buffer, the string is printed in multiple lines.
*
* @param logPriority one of {@link android.util.Log#VERBOSE},
* {@link android.util.Log#DEBUG},
* {@link android.util.Log#INFO},
* {@link android.util.Log#WARN},
* {@link android.util.Log#ERROR},
* {@link android.util.Log#ASSERT}
* @param string string to be printed
*/
public static void printToLogcat(final int logPriority, final String string) {
final int LOGGER_ENTRY_MAX_LEN = 4 * 1000;
String remainingString = string;
do {
if (remainingString.length() <= LOGGER_ENTRY_MAX_LEN) {
android.util.Log.println(logPriority, FFmpegKitConfig.TAG, remainingString);
remainingString = "";
} else {
final int index = remainingString.substring(0, LOGGER_ENTRY_MAX_LEN).lastIndexOf('\n');
if (index < 0) {
android.util.Log.println(logPriority, FFmpegKitConfig.TAG, remainingString.substring(0, LOGGER_ENTRY_MAX_LEN));
remainingString = remainingString.substring(LOGGER_ENTRY_MAX_LEN);
} else {
android.util.Log.println(logPriority, FFmpegKitConfig.TAG, remainingString.substring(0, index));
remainingString = remainingString.substring(index);
}
}
} while (remainingString.length() > 0);
}
/**
* <p>Sets an environment variable.
*
* @param variableName environment variable name
* @param variableValue environment variable value
* @return zero on success, non-zero on error
*/
public static int setEnvironmentVariable(final String variableName, final String variableValue) {
return setNativeEnvironmentVariable(variableName, variableValue);
}
/**
* <p>Registers a new ignored signal. Ignored signals are not handled by <code>FFmpegKit</code>
* library.
*
* @param signal signal to be ignored
*/
public static void ignoreSignal(final Signal signal) {
ignoreNativeSignal(signal.getValue());
}
/**
* <p>Synchronously executes the FFmpeg session provided.
*
* @param ffmpegSession FFmpeg session which includes command options/arguments
*/
public static void ffmpegExecute(final FFmpegSession ffmpegSession) {
addSession(ffmpegSession);
ffmpegSession.startRunning();
try {
final int returnCode = nativeFFmpegExecute(ffmpegSession.getSessionId(), ffmpegSession.getArguments());
ffmpegSession.complete(new ReturnCode(returnCode));
} catch (final Exception e) {
ffmpegSession.fail(e);
android.util.Log.w(FFmpegKitConfig.TAG, String.format("FFmpeg execute failed: %s.%s", FFmpegKit.argumentsToString(ffmpegSession.getArguments()), Exceptions.getStackTraceString(e)));
}
}
/**
* <p>Synchronously executes the FFprobe session provided.
*
* @param ffprobeSession FFprobe session which includes command options/arguments
*/
public static void ffprobeExecute(final FFprobeSession ffprobeSession) {
addSession(ffprobeSession);
ffprobeSession.startRunning();
try {
final int returnCode = nativeFFprobeExecute(ffprobeSession.getSessionId(), ffprobeSession.getArguments());
ffprobeSession.complete(new ReturnCode(returnCode));
} catch (final Exception e) {
ffprobeSession.fail(e);
android.util.Log.w(FFmpegKitConfig.TAG, String.format("FFprobe execute failed: %s.%s", FFmpegKit.argumentsToString(ffprobeSession.getArguments()), Exceptions.getStackTraceString(e)));
}
}
/**
* <p>Synchronously executes the media information session provided.
*
* @param mediaInformationSession media information session which includes command options/arguments
* @param waitTimeout max time to wait until media information is transmitted
*/
public static void getMediaInformationExecute(final MediaInformationSession mediaInformationSession, final int waitTimeout) {
addSession(mediaInformationSession);
mediaInformationSession.startRunning();
try {
final int returnCodeValue = nativeFFprobeExecute(mediaInformationSession.getSessionId(), mediaInformationSession.getArguments());
final ReturnCode returnCode = new ReturnCode(returnCodeValue);
mediaInformationSession.complete(returnCode);
if (returnCode.isSuccess()) {
MediaInformation mediaInformation = MediaInformationJsonParser.fromWithError(mediaInformationSession.getAllLogsAsString(waitTimeout));
mediaInformationSession.setMediaInformation(mediaInformation);
}
} catch (final Exception e) {
mediaInformationSession.fail(e);
android.util.Log.w(FFmpegKitConfig.TAG, String.format("Get media information execute failed: %s.%s", FFmpegKit.argumentsToString(mediaInformationSession.getArguments()), Exceptions.getStackTraceString(e)));
}
}
/**
* <p>Asynchronously executes the FFmpeg session provided.
*
* @param ffmpegSession FFmpeg session which includes command options/arguments
*/
public static void asyncFFmpegExecute(final FFmpegSession ffmpegSession) {
addSession(ffmpegSession);
AsyncFFmpegExecuteTask asyncFFmpegExecuteTask = new AsyncFFmpegExecuteTask(ffmpegSession);
Future<?> future = asyncExecutorService.submit(asyncFFmpegExecuteTask);
ffmpegSession.setFuture(future);
}
/**
* <p>Asynchronously executes the FFmpeg session provided.
*
* @param ffmpegSession FFmpeg session which includes command options/arguments
* @param executorService executor service that will be used to run this asynchronous operation
*/
public static void asyncFFmpegExecute(final FFmpegSession ffmpegSession, final ExecutorService executorService) {
addSession(ffmpegSession);
AsyncFFmpegExecuteTask asyncFFmpegExecuteTask = new AsyncFFmpegExecuteTask(ffmpegSession);
Future<?> future = executorService.submit(asyncFFmpegExecuteTask);
ffmpegSession.setFuture(future);
}
/**
* <p>Asynchronously executes the FFprobe session provided.
*
* @param ffprobeSession FFprobe session which includes command options/arguments
*/
public static void asyncFFprobeExecute(final FFprobeSession ffprobeSession) {
addSession(ffprobeSession);
AsyncFFprobeExecuteTask asyncFFmpegExecuteTask = new AsyncFFprobeExecuteTask(ffprobeSession);
Future<?> future = asyncExecutorService.submit(asyncFFmpegExecuteTask);
ffprobeSession.setFuture(future);
}
/**
* <p>Asynchronously executes the FFprobe session provided.
*
* @param ffprobeSession FFprobe session which includes command options/arguments
* @param executorService executor service that will be used to run this asynchronous operation
*/
public static void asyncFFprobeExecute(final FFprobeSession ffprobeSession, final ExecutorService executorService) {
addSession(ffprobeSession);
AsyncFFprobeExecuteTask asyncFFmpegExecuteTask = new AsyncFFprobeExecuteTask(ffprobeSession);
Future<?> future = executorService.submit(asyncFFmpegExecuteTask);
ffprobeSession.setFuture(future);
}
/**
* <p>Asynchronously executes the media information session provided.
*
* @param mediaInformationSession media information session which includes command options/arguments
* @param waitTimeout max time to wait until media information is transmitted
*/
public static void asyncGetMediaInformationExecute(final MediaInformationSession mediaInformationSession, final int waitTimeout) {
addSession(mediaInformationSession);
AsyncGetMediaInformationTask asyncGetMediaInformationTask = new AsyncGetMediaInformationTask(mediaInformationSession, waitTimeout);
Future<?> future = asyncExecutorService.submit(asyncGetMediaInformationTask);
mediaInformationSession.setFuture(future);
}
/**
* <p>Asynchronously executes the media information session provided.
*
* @param mediaInformationSession media information session which includes command options/arguments
* @param executorService executor service that will be used to run this asynchronous operation
* @param waitTimeout max time to wait until media information is transmitted
*/
public static void asyncGetMediaInformationExecute(final MediaInformationSession mediaInformationSession, final ExecutorService executorService, final int waitTimeout) {
addSession(mediaInformationSession);
AsyncGetMediaInformationTask asyncGetMediaInformationTask = new AsyncGetMediaInformationTask(mediaInformationSession, waitTimeout);
Future<?> future = executorService.submit(asyncGetMediaInformationTask);
mediaInformationSession.setFuture(future);
}
/**
* Returns the maximum number of async sessions that will be executed in parallel.
*
* @return maximum number of async sessions that will be executed in parallel
*/
public static int getAsyncConcurrencyLimit() {
return asyncConcurrencyLimit;
}
/**
* Sets the maximum number of async sessions that will be executed in parallel. If more
* sessions are submitted those will be queued.
*
* @param asyncConcurrencyLimit new async concurrency limit
*/
public static void setAsyncConcurrencyLimit(final int asyncConcurrencyLimit) {
if (asyncConcurrencyLimit > 0) {
/* SET THE NEW LIMIT */
FFmpegKitConfig.asyncConcurrencyLimit = asyncConcurrencyLimit;
ExecutorService oldAsyncExecutorService = FFmpegKitConfig.asyncExecutorService;
/* CREATE THE NEW ASYNC THREAD POOL */
FFmpegKitConfig.asyncExecutorService = Executors.newFixedThreadPool(asyncConcurrencyLimit);
/* STOP THE OLD ASYNC THREAD POOL */
oldAsyncExecutorService.shutdown();
}
}
/**
* <p>Sets a global callback function to redirect FFmpeg/FFprobe logs.
*
* @param logCallback log callback function or null to disable a previously defined
* callback
*/
public static void enableLogCallback(final LogCallback logCallback) {
globalLogCallbackFunction = logCallback;
}
/**
* <p>Sets a global callback function to redirect FFmpeg statistics.
*
* @param statisticsCallback statistics callback function or null to disable a previously
* defined callback
*/
public static void enableStatisticsCallback(final StatisticsCallback statisticsCallback) {
globalStatisticsCallbackFunction = statisticsCallback;
}
/**
* <p>Sets a global callback function to receive execution results.
*
* @param executeCallback execute callback function or null to disable a previously
* defined callback
*/
public static void enableExecuteCallback(final ExecuteCallback executeCallback) {
globalExecuteCallbackFunction = executeCallback;
}
/**
* <p>Returns the global execute callback function.
*
* @return global execute callback function
*/
static ExecuteCallback getExecuteCallback() {
return globalExecuteCallbackFunction;
}
/**
* Returns the current log level.
*
* @return current log level
*/
public static Level getLogLevel() {
return activeLogLevel;
}
/**
* Sets the log level.
*
* @param level new log level
*/
public static void setLogLevel(final Level level) {
if (level != null) {
activeLogLevel = level;
setNativeLogLevel(level.getValue());
}
}
/**
* <p>Converts the given Structured Access Framework Uri (<code>"content:…"</code>) into an
* input/output url that can be used in FFmpeg and FFprobe commands.
*
* <p>Requires API Level >= 19. On older API levels it returns an empty url.
*
* @return input/output url that can be passed to FFmpegKit or FFprobeKit
*/
private static String getSafParameter(final Context context, final Uri uri, final String openMode) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
android.util.Log.i(TAG, String.format("getSafParameter is not supported on API Level %d", Build.VERSION.SDK_INT));
return "";
}
String displayName = "unknown";
try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME));
}
} catch (final Throwable t) {
android.util.Log.e(TAG, String.format("Failed to get %s column for %s.%s", DocumentsContract.Document.COLUMN_DISPLAY_NAME, uri.toString(), Exceptions.getStackTraceString(t)));
}
int fd = -1;
try {
ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, openMode);
fd = parcelFileDescriptor.getFd();
pfdMap.put(fd, parcelFileDescriptor);
} catch (final Throwable t) {
android.util.Log.e(TAG, String.format("Failed to obtain %s parcelFileDescriptor for %s.%s", openMode, uri.toString(), Exceptions.getStackTraceString(t)));
}
// workaround for https://issuetracker.google.com/issues/162440528: ANDROID_CREATE_DOCUMENT generating file names like "transcode.mp3 (2)"
if (displayName.lastIndexOf('.') > 0 && displayName.lastIndexOf(' ') > displayName.lastIndexOf('.')) {
String extension = displayName.substring(displayName.lastIndexOf('.'), displayName.lastIndexOf(' '));
displayName += extension;
}
// spaces can break argument list parsing, see https://github.com/alexcohn/mobile-ffmpeg/pull/1#issuecomment-688643836
final char NBSP = (char) 0xa0;
return "saf:" + fd + "/" + displayName.replace(' ', NBSP);
}
/**
* <p>Converts the given Structured Access Framework Uri (<code>"content:…"</code>) into an
* input url that can be used in FFmpeg and FFprobe commands.
*
* <p>Requires API Level ≥ 19. On older API levels it returns an empty url.
*
* @param context application context
* @param uri saf uri
* @return input url that can be passed to FFmpegKit or FFprobeKit
*/
public static String getSafParameterForRead(final Context context, final Uri uri) {
return getSafParameter(context, uri, "r");
}
/**
* <p>Converts the given Structured Access Framework Uri (<code>"content:…"</code>) into an
* output url that can be used in FFmpeg and FFprobe commands.
*
* <p>Requires API Level ≥ 19. On older API levels it returns an empty url.
*
* @param context application context
* @param uri saf uri
* @return output url that can be passed to FFmpegKit or FFprobeKit
*/
public static String getSafParameterForWrite(final Context context, final Uri uri) {
return getSafParameter(context, uri, "w");
}
/**
* Called by saf_wrapper from native library to close a parcel file descriptor.
*
* @param fd parcel file descriptor created for a saf uri
*/
private static void closeParcelFileDescriptor(final int fd) {
try {
ParcelFileDescriptor pfd = pfdMap.get(fd);
if (pfd != null) {
pfd.close();
pfdMap.delete(fd);
}
} catch (final Throwable t) {
android.util.Log.e(TAG, String.format("Failed to close file descriptor: %d.%s", fd, Exceptions.getStackTraceString(t)));
}
}
/**
* Returns the session history size.
*
* @return session history size
*/
public static int getSessionHistorySize() {
return sessionHistorySize;
}
/**
* Sets the session history size.
*
* @param sessionHistorySize session history size, should be smaller than 1000
*/
public static void setSessionHistorySize(final int sessionHistorySize) {
if (sessionHistorySize >= 1000) {
/*
* THERE IS A HARD LIMIT ON THE NATIVE SIDE. HISTORY SIZE MUST BE SMALLER THAN 1000
*/
throw new IllegalArgumentException("Session history size must not exceed the hard limit!");
} else if (sessionHistorySize > 0) {
FFmpegKitConfig.sessionHistorySize = sessionHistorySize;
}
}
/**
* Adds a session to the session history.
*
* @param session new session
*/
static void addSession(final Session session) {
synchronized (sessionHistoryLock) {
/*
* ASYNC SESSIONS CALL THIS METHOD TWICE
* THIS CHECK PREVENTS ADDING THE SAME SESSION TWICE
*/
final boolean sessionAlreadyAdded = sessionHistoryMap.containsKey(session.getSessionId());
if (!sessionAlreadyAdded) {
sessionHistoryMap.put(session.getSessionId(), session);
sessionHistoryList.add(session);
if (sessionHistoryList.size() > sessionHistorySize) {
try {
sessionHistoryList.remove(0);
} catch (final IndexOutOfBoundsException ignored) {
}
}
}
}
}
/**
* Returns the session specified with <code>sessionId</code> from the session history.
*
* @param sessionId session identifier
* @return session specified with sessionId or null if it is not found in the history
*/
public static Session getSession(final long sessionId) {
synchronized (sessionHistoryLock) {
return sessionHistoryMap.get(sessionId);
}
}
/**
* Returns the last session created from the session history.
*
* @return the last session created or null if session history is empty
*/
public static Session getLastSession() {
synchronized (sessionHistoryLock) {
if (sessionHistoryList.size() > 0) {
return sessionHistoryList.get(sessionHistoryList.size() - 1);
}
}
return null;
}
/**