Config.java
24.6 KB
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
/*
* Copyright (c) 2018 Taner Sener
*
* This file is part of MobileFFmpeg.
*
* MobileFFmpeg 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.
*
* MobileFFmpeg 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 MobileFFmpeg. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.mobileffmpeg;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.mobile.ffmpeg.Abi;
import com.mobile.ffmpeg.CameraSupport;
import com.mobile.ffmpeg.FFmpeg;
import com.mobile.ffmpeg.Level;
import com.mobile.ffmpeg.LogCallback;
import com.mobile.ffmpeg.LogMessage;
import com.mobile.ffmpeg.Packages;
import com.mobile.ffmpeg.Statistics;
import com.mobile.ffmpeg.StatisticsCallback;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
/**
* <p>This class is used to configure MobileFFmpeg library utilities/tools.
*
* <p>1. {@link LogCallback}: This class redirects FFmpeg/FFprobe output to Logcat by default. As
* an alternative, it is possible not to print messages to Logcat and pass them to a
* {@link LogCallback} function. This function can decide whether to print these logs, show them
* inside another container or ignore them.
*
* <p>2. {@link #setLogLevel(Level)}/{@link #getLogLevel()}: Use this methods to set/get
* FFmpeg/FFprobe log severity.
*
* <p>3. {@link StatisticsCallback}: It is possible to receive statistics about an ongoing
* operation by defining a {@link StatisticsCallback} function or by calling
* {@link #getLastReceivedStatistics()} method.
*
* <p>4. Font configuration: It is possible to register custom fonts with
* {@link #setFontconfigConfigurationPath(String)} and
* {@link #setFontDirectory(Context, String, Map)} methods.
*
*/
public class Config {
public static final int RETURN_CODE_SUCCESS = 0;
public static final int RETURN_CODE_CANCEL = 255;
private static int lastReturnCode = 0;
/**
* Defines tag used for logging.
*/
public static final String TAG = "mobile-ffmpeg";
public static final String MOBILE_FFMPEG_PIPE_PREFIX = "mf_pipe_";
private static LogCallback logCallbackFunction;
private static Level activeLogLevel;
private static StatisticsCallback statisticsCallbackFunction;
private static Statistics lastReceivedStatistics;
private static int lastCreatedPipeIndex;
static {
Log.i(Config.TAG, "Loading mobile-ffmpeg.");
/* LOAD NOT-LOADED LIBRARIES ON API < 21 */
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
final List<String> externalLibrariesEnabled = getExternalLibraries();
if (externalLibrariesEnabled.contains("tesseract") || externalLibrariesEnabled.contains("x265") || externalLibrariesEnabled.contains("snappy") || externalLibrariesEnabled.contains("openh264")) {
// libc++_shared.so included only when tesseract or x265 is enabled
System.loadLibrary("c++_shared");
}
System.loadLibrary("cpufeatures");
System.loadLibrary("avutil");
System.loadLibrary("swscale");
System.loadLibrary("swresample");
System.loadLibrary("avcodec");
System.loadLibrary("avformat");
System.loadLibrary("avfilter");
System.loadLibrary("avdevice");
}
/* ALL MOBILE-FFMPEG LIBRARIES LOADED AT STARTUP */
Abi.class.getName();
FFmpeg.class.getName();
/*
* NEON supported arm-v7a library has a different name
*/
boolean nativeLibraryLoaded = false;
if (AbiDetect.ARM_V7A.equals(AbiDetect.getNativeAbi())) {
if (AbiDetect.isNativeLTSBuild()) {
/*
* IF CPU SUPPORTS ARM-V7A-NEON THE TRY TO LOAD IT FIRST. IF NOT LOAD DEFAULT ARM-V7A
*/
try {
System.loadLibrary("mobileffmpeg_armv7a_neon");
nativeLibraryLoaded = true;
AbiDetect.setArmV7aNeonLoaded(true);
} catch (final UnsatisfiedLinkError e) {
Log.i(Config.TAG, "NEON supported armeabi-v7a library not found. Loading default armeabi-v7a library.", e);
}
} else {
AbiDetect.setArmV7aNeonLoaded(true);
}
}
if (!nativeLibraryLoaded) {
System.loadLibrary("mobileffmpeg");
}
Log.i(Config.TAG, String.format("Loaded mobile-ffmpeg-%s-%s-%s-%s.", getPackageName(), AbiDetect.getAbi(), getVersion(), getBuildDate()));
/* NATIVE LOG LEVEL IS RECEIVED ONLY ON STARTUP */
activeLogLevel = Level.from(getNativeLogLevel());
lastReceivedStatistics = new Statistics();
enableRedirection();
lastCreatedPipeIndex = 0;
}
/**
* Default constructor hidden.
*/
private Config() {
}
/**
* <p>Enables log and statistics redirection.
* <p>When redirection is not enabled FFmpeg/FFprobe logs are printed to stderr. By enabling
* redirection, they are routed to Logcat and can be routed further to a callback function.
* <p>Statistics redirection behaviour is similar. Statistics are not printed at all if
* redirection is not enabled. If it is enabled then it is possible to define a statistics
* callback function but if you don't, they are not printed anywhere and only saved as
* <code>lastReceivedStatistics</code> data which can be polled with
* {@link #getLastReceivedStatistics()}.
* <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.
*/
public static void disableRedirection() {
disableNativeRedirection();
}
/**
* Returns log level.
*
* @return log level
*/
public static Level getLogLevel() {
return activeLogLevel;
}
/**
* Sets log level.
*
* @param level log level
*/
public static void setLogLevel(final Level level) {
if (level != null) {
activeLogLevel = level;
setNativeLogLevel(level.getValue());
}
}
/**
* <p>Sets a callback function to redirect FFmpeg/FFprobe logs.
*
* @param newLogCallback new log callback function or NULL to disable a previously defined callback
*/
public static void enableLogCallback(final LogCallback newLogCallback) {
logCallbackFunction = newLogCallback;
}
/**
* <p>Sets a callback function to redirect FFmpeg statistics.
*
* @param statisticsCallback new statistics callback function or NULL to disable a previously defined callback
*/
public static void enableStatisticsCallback(final StatisticsCallback statisticsCallback) {
statisticsCallbackFunction = statisticsCallback;
}
/**
* <p>Log redirection method called by JNI/native part.
*
* @param levelValue log level as defined in {@link Level}
* @param logMessage redirected log message
*/
private static void log(final int levelValue, final byte[] logMessage) {
final Level level = Level.from(levelValue);
final String text = new String(logMessage);
// 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;
}
if (logCallbackFunction != null) {
try {
logCallbackFunction.apply(new LogMessage(level, text));
} catch (final Exception e) {
Log.e(Config.TAG, "Exception thrown inside LogCallback block", e);
}
} else {
switch (level) {
case AV_LOG_QUIET: {
// PRINT NO OUTPUT
}
break;
case AV_LOG_TRACE:
case AV_LOG_DEBUG: {
Log.d(TAG, text);
}
break;
case AV_LOG_STDERR:
case AV_LOG_VERBOSE: {
Log.v(TAG, text);
}
break;
case AV_LOG_INFO: {
Log.i(TAG, text);
}
break;
case AV_LOG_WARNING: {
Log.w(TAG, text);
}
break;
case AV_LOG_ERROR:
case AV_LOG_FATAL:
case AV_LOG_PANIC: {
Log.e(TAG, text);
}
break;
default: {
Log.v(TAG, text);
}
break;
}
}
}
/**
* <p>Statistics redirection method called by JNI/native part.
*
* @param videoFrameNumber last processed frame number for videos
* @param videoFps frames processed per second 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 int videoFrameNumber, final float videoFps,
final float videoQuality, final long size, final int time,
final double bitrate, final double speed) {
final Statistics newStatistics = new Statistics(videoFrameNumber, videoFps, videoQuality, size, time, bitrate, speed);
lastReceivedStatistics.update(newStatistics);
if (statisticsCallbackFunction != null) {
try {
statisticsCallbackFunction.apply(lastReceivedStatistics);
} catch (final Exception e) {
Log.e(Config.TAG, "Exception thrown inside StatisticsCallback block", e);
}
}
}
/**
* <p>Returns the last received statistics data.
*
* @return last received statistics data
*/
public static Statistics getLastReceivedStatistics() {
return lastReceivedStatistics;
}
/**
* <p>Resets last received statistics. It is recommended to call it before starting a new execution.
*/
public static void resetStatistics() {
lastReceivedStatistics = new Statistics();
}
/**
* <p>Sets and overrides <code>fontconfig</code> configuration directory.
*
* @param path directory which 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 fonts inside the given path, so they are available to use in FFmpeg filters.
*
* <p>Note that you need to build <code>MobileFFmpeg</code> with <code>fontconfig</code>
* enabled or use a prebuilt package with <code>fontconfig</code> inside to use this feature.
*
* @param context application context to access application data
* @param fontDirectoryPath directory which 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) {
final File cacheDir = context.getCacheDir();
int validFontNameMappingCount = 0;
final File tempConfigurationDirectory = new File(cacheDir, ".mobileffmpeg");
if (!tempConfigurationDirectory.exists()) {
boolean tempFontConfDirectoryCreated = tempConfigurationDirectory.mkdirs();
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();
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 String fontConfig = "<?xml version=\"1.0\"?>\n" +
"<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n" +
"<fontconfig>\n" +
" <dir>.</dir>\n" +
" <dir>" + fontDirectoryPath + "</dir>\n" +
fontNameMappingBlock +
"</fontconfig>";
final AtomicReference<FileOutputStream> reference = new AtomicReference<>();
try {
final FileOutputStream outputStream = new FileOutputStream(fontConfiguration);
reference.set(outputStream);
outputStream.write(fontConfig.getBytes());
outputStream.flush();
Log.d(TAG, String.format("Saved new temporary font configuration with %d font name mappings.", validFontNameMappingCount));
setFontconfigConfigurationPath(tempConfigurationDirectory.getAbsolutePath());
Log.d(TAG, String.format("Font directory %s registered successfully.", fontDirectoryPath));
} catch (final IOException e) {
Log.e(TAG, String.format("Failed to set font directory: %s.", fontDirectoryPath), e);
} finally {
if (reference.get() != null) {
try {
reference.get().close();
} catch (IOException e) {
// DO NOT PRINT THIS ERROR
}
}
}
}
/**
* <p>Returns package name.
*
* @return guessed package name according to supported external libraries
* @since 3.0
*/
public static String getPackageName() {
return Packages.getPackageName();
}
/**
* <p>Returns supported external libraries.
*
* @return list of supported external libraries
* @since 3.0
*/
public static List<String> getExternalLibraries() {
return Packages.getExternalLibraries();
}
/**
* <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 named pipe
*/
public static String registerNewFFmpegPipe(final Context context) {
// PIPES ARE CREATED UNDER THE CACHE DIRECTORY
final File cacheDir = context.getCacheDir();
final String newFFmpegPipePath = cacheDir + File.separator + MOBILE_FFMPEG_PIPE_PREFIX + (++lastCreatedPipeIndex);
// FIRST CLOSE OLD PIPES WITH THE SAME NAME
closeFFmpegPipe(newFFmpegPipePath);
int rc = registerNewNativeFFmpegPipe(newFFmpegPipePath);
if (rc == 0) {
return newFFmpegPipePath;
} else {
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 ffmpeg pipe
*/
public static void closeFFmpegPipe(final String ffmpegPipePath) {
File file = new File(ffmpegPipePath);
if (file.exists()) {
file.delete();
}
}
/**
* Returns the list of camera ids supported.
*
* @param context application context
* @return the list of camera ids supported or an empty list if no supported camera is 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 FFmpeg version bundled within the library.
*
* @return FFmpeg version
*/
public static String getFFmpegVersion() {
return getNativeFFmpegVersion();
}
/**
* <p>Returns MobileFFmpeg library version.
*
* @return MobileFFmpeg version
*/
public static String getVersion() {
if (AbiDetect.isNativeLTSBuild()) {
return String.format("%s-lts", getNativeVersion());
} else {
return getNativeVersion();
}
}
/**
* <p>Returns whether MobileFFmpeg release is a long term release or not.
*
* @return YES or NO
*/
public static boolean isLTSBuild() {
return AbiDetect.isNativeLTSBuild();
}
/**
* <p>Returns MobileFFmpeg library build date.
*
* @return MobileFFmpeg library build date
*/
public static String getBuildDate() {
return getNativeBuildDate();
}
/**
* <p>Returns return code of last executed command.
*
* @return return code of last executed command
* @since 3.0
*/
public static int getLastReturnCode() {
return lastReturnCode;
}
/**
* <p>Returns log output of last executed single FFmpeg/FFprobe command.
*
* <p>This method does not support executing multiple concurrent commands. If you execute
* multiple commands at the same time, this method will return output from all executions.
*
* <p>Please note that disabling redirection using {@link Config#disableRedirection()} method
* also disables this functionality.
*
* @return output of the last executed command
* @since 3.0
*/
public static String getLastCommandOutput() {
String nativeLastCommandOutput = getNativeLastCommandOutput();
if (nativeLastCommandOutput != null) {
// REPLACING CH(13) WITH CH(10)
nativeLastCommandOutput = nativeLastCommandOutput.replace('\r', '\n');
}
return nativeLastCommandOutput;
}
/**
* <p>Prints the output of the last executed FFmpeg/FFprobe command to the Logcat at the
* specified priority.
*
* <p>This method does not support executing multiple concurrent commands. If you execute
* multiple commands at the same time, this method will print output from all executions.
*
* @param logPriority one of {@link Log#VERBOSE}, {@link Log#DEBUG}, {@link Log#INFO},
* {@link Log#WARN}, {@link Log#ERROR}, {@link Log#ASSERT}
* @since 4.3
*/
public static void printLastCommandOutput(int logPriority) {
final int LOGGER_ENTRY_MAX_LEN = 4 * 1000;
String buffer = getLastCommandOutput();
do {
if (buffer.length() <= LOGGER_ENTRY_MAX_LEN) {
Log.println(logPriority, Config.TAG, buffer);
buffer = "";
} else {
final int index = buffer.substring(0, LOGGER_ENTRY_MAX_LEN).lastIndexOf('\n');
if (index < 0) {
Log.println(logPriority, Config.TAG, buffer.substring(0, LOGGER_ENTRY_MAX_LEN));
buffer = buffer.substring(LOGGER_ENTRY_MAX_LEN);
} else {
Log.println(logPriority, Config.TAG, buffer.substring(0, index));
buffer = buffer.substring(index);
}
}
} while (buffer.length() > 0);
}
/**
* Updates return code value for the last executed command.
*
* @param newLastReturnCode new last return code value
*/
public static void setLastReturnCode(int newLastReturnCode) {
lastReturnCode = newLastReturnCode;
}
/**
* <p>Enables native redirection. Necessary for log and statistics callback functions.
*/
private static native void enableNativeRedirection();
/**
* <p>Disables native redirection
*/
private static native void disableNativeRedirection();
/**
* Sets native log level
*
* @param level log level
*/
private static native void setNativeLogLevel(int level);
/**
* Returns native log level.
*
* @return log level
*/
private static native int getNativeLogLevel();
/**
* <p>Returns FFmpeg version bundled within the library natively.
*
* @return FFmpeg version
*/
native static String getNativeFFmpegVersion();
/**
* <p>Returns MobileFFmpeg library version natively.
*
* @return MobileFFmpeg version
*/
native static String getNativeVersion();
/**
* <p>Synchronously executes FFmpeg natively with arguments provided.
*
* @param arguments FFmpeg command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
public native static int nativeFFmpegExecute(final String[] arguments);
/**
* <p>Cancels an ongoing FFmpeg operation natively. This function does not wait for termination
* to complete and returns immediately.
*/
public native static void nativeFFmpegCancel();
/**
* <p>Synchronously executes FFprobe natively with arguments provided.
*
* @param arguments FFprobe command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
public native static int nativeFFprobeExecute(final String[] arguments);
/**
* <p>Creates natively a new named pipe to use in <code>FFmpeg</code> operations.
*
* <p>Please note that creator is responsible of closing created pipes.
*
* @param ffmpegPipePath full path of ffmpeg pipe
* @return zero on successful creation, non-zero on error
*/
public native static int registerNewNativeFFmpegPipe(final String ffmpegPipePath);
/**
* <p>Returns MobileFFmpeg library build date natively.
*
* @return MobileFFmpeg library build date
*/
public native static String getNativeBuildDate();
/**
* <p>Sets an environment variable natively.
*
* @param variableName environment variable name
* @param variableValue environment variable value
* @return zero on success, non-zero on error
*/
public native static int setNativeEnvironmentVariable(final String variableName, final String variableValue);
/**
* <p>Returns log output of the last executed single command natively.
*
* @return output of the last executed single command
*/
native static String getNativeLastCommandOutput();
}