flutter_ffmpeg.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*
  2. * Copyright (c) 2019 Taner Sener
  3. *
  4. * This file is part of FlutterFFmpeg.
  5. *
  6. * FlutterFFmpeg is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Lesser General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * FlutterFFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with FlutterFFmpeg. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. import 'dart:async';
  20. import 'package:flutter/services.dart';
  21. class FlutterFFmpegConfig {
  22. static const MethodChannel _methodChannel =
  23. const MethodChannel('flutter_ffmpeg');
  24. static const EventChannel _eventChannel =
  25. const EventChannel('flutter_ffmpeg_event');
  26. Function(int level, String message) logCallback;
  27. Function(
  28. int time,
  29. int size,
  30. double bitrate,
  31. double speed,
  32. int videoFrameNumber,
  33. double videoQuality,
  34. double videoFps) statisticsCallback;
  35. FlutterFFmpegConfig() {
  36. logCallback = null;
  37. statisticsCallback = null;
  38. print("Loading flutter-ffmpeg.");
  39. _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  40. enableLogs();
  41. enableStatistics();
  42. enableRedirection();
  43. getPlatform().then((name) => print("Loaded flutter-ffmpeg-$name."));
  44. }
  45. void _onEvent(Object event) {
  46. if (event is Map<dynamic, dynamic>) {
  47. final Map<String, dynamic> eventMap = event.cast();
  48. final Map<dynamic, dynamic> logEvent =
  49. eventMap['FlutterFFmpegLogCallback'];
  50. final Map<dynamic, dynamic> statisticsEvent =
  51. eventMap['FlutterFFmpegStatisticsCallback'];
  52. if (logEvent != null) {
  53. int level = logEvent['level'];
  54. String message = logEvent['log'];
  55. if (this.logCallback == null) {
  56. if (message.length > 0) {
  57. // PRINT ALREADY ADDS NEW LINE. SO REMOVE THIS ONE
  58. if (message.endsWith('\n')) {
  59. print(message.substring(0, message.length - 1));
  60. } else {
  61. print(message);
  62. }
  63. }
  64. } else {
  65. this.logCallback(level, message);
  66. }
  67. }
  68. if (statisticsEvent != null) {
  69. if (this.statisticsCallback != null) {
  70. int time = statisticsEvent['time'];
  71. int size = statisticsEvent['size'];
  72. double bitrate = _doublePrecision(statisticsEvent['bitrate'], 2);
  73. double speed = _doublePrecision(statisticsEvent['speed'], 2);
  74. int videoFrameNumber = statisticsEvent['videoFrameNumber'];
  75. double videoQuality =
  76. _doublePrecision(statisticsEvent['videoQuality'], 2);
  77. double videoFps = _doublePrecision(statisticsEvent['videoFps'], 2);
  78. this.statisticsCallback(time, size, bitrate, speed, videoFrameNumber,
  79. videoQuality, videoFps);
  80. }
  81. }
  82. }
  83. }
  84. void _onError(Object error) {
  85. print('Event error: $error');
  86. }
  87. double _doublePrecision(double value, int precision) {
  88. if (value == null) {
  89. return 0;
  90. } else {
  91. return num.parse(value.toStringAsFixed(precision));
  92. }
  93. }
  94. /// Returns FFmpeg version bundled within the library.
  95. Future<String> getFFmpegVersion() async {
  96. try {
  97. final Map<dynamic, dynamic> result =
  98. await _methodChannel.invokeMethod('getFFmpegVersion');
  99. return result['version'];
  100. } on PlatformException catch (e) {
  101. print("Plugin error: ${e.message}");
  102. return null;
  103. }
  104. }
  105. /// Returns platform name where library is loaded.
  106. Future<String> getPlatform() async {
  107. try {
  108. final Map<dynamic, dynamic> result =
  109. await _methodChannel.invokeMethod('getPlatform');
  110. return result['platform'];
  111. } on PlatformException catch (e) {
  112. print("Plugin error: ${e.message}");
  113. return null;
  114. }
  115. }
  116. /// Enables redirection
  117. Future<void> enableRedirection() async {
  118. try {
  119. await _methodChannel.invokeMethod('enableRedirection');
  120. } on PlatformException catch (e) {
  121. print("Plugin error: ${e.message}");
  122. }
  123. }
  124. /// Disables log and statistics redirection. By default redirection is enabled in constructor.
  125. /// When redirection is enabled FFmpeg logs are printed to console and can be routed further to a callback function.
  126. /// By disabling redirection, logs are redirected to stderr.
  127. /// Statistics redirection behaviour is similar. Statistics are not printed at all if redirection is not enabled.
  128. /// If it is enabled then it is possible to define a statistics callback function but if you don't, they are not
  129. /// printed anywhere and only saved as codelastReceivedStatistics data which can be polled with
  130. /// [getLastReceivedStatistics()].
  131. Future<void> disableRedirection() async {
  132. try {
  133. await _methodChannel.invokeMethod('disableRedirection');
  134. } on PlatformException catch (e) {
  135. print("Plugin error: ${e.message}");
  136. }
  137. }
  138. /// Returns log level.
  139. Future<int> getLogLevel() async {
  140. try {
  141. final Map<dynamic, dynamic> result =
  142. await _methodChannel.invokeMethod('getLogLevel');
  143. return result['level'];
  144. } on PlatformException catch (e) {
  145. print("Plugin error: ${e.message}");
  146. return -1;
  147. }
  148. }
  149. /// Sets log level.
  150. Future<void> setLogLevel(int logLevel) async {
  151. try {
  152. await _methodChannel.invokeMethod('setLogLevel', {'level': logLevel});
  153. } on PlatformException catch (e) {
  154. print("Plugin error: ${e.message}");
  155. }
  156. }
  157. /// Enables log events
  158. Future<void> enableLogs() async {
  159. try {
  160. await _methodChannel.invokeMethod('enableLogs');
  161. } on PlatformException catch (e) {
  162. print("Plugin error: ${e.message}");
  163. }
  164. }
  165. /// Disables log functionality of the library. Logs will not be printed to console and log callback will be disabled.
  166. /// Note that log functionality is enabled by default.
  167. Future<void> disableLogs() async {
  168. try {
  169. await _methodChannel.invokeMethod('disableLogs');
  170. } on PlatformException catch (e) {
  171. print("Plugin error: ${e.message}");
  172. }
  173. }
  174. /// Enables statistics events.
  175. Future<void> enableStatistics() async {
  176. try {
  177. await _methodChannel.invokeMethod('enableStatistics');
  178. } on PlatformException catch (e) {
  179. print("Plugin error: ${e.message}");
  180. }
  181. }
  182. /// Disables statistics functionality of the library. Statistics callback will be disabled but the last received
  183. /// statistics data will be still available.
  184. /// Note that statistics functionality is enabled by default.
  185. Future<void> disableStatistics() async {
  186. try {
  187. await _methodChannel.invokeMethod('disableStatistics');
  188. } on PlatformException catch (e) {
  189. print("Plugin error: ${e.message}");
  190. }
  191. }
  192. /// Sets a callback to redirect FFmpeg logs. [newCallback] is a new log callback function, use null to disable a previously defined callback
  193. void enableLogCallback(Function(int level, String message) newCallback) {
  194. try {
  195. this.logCallback = newCallback;
  196. } on PlatformException catch (e) {
  197. print("Plugin error: ${e.message}");
  198. }
  199. }
  200. /// Sets a callback to redirect FFmpeg statistics. [newCallback] is a new statistics callback function, use null to disable a previously defined callback
  201. void enableStatisticsCallback(
  202. Function(int time, int size, double bitrate, double speed,
  203. int videoFrameNumber, double videoQuality, double videoFps)
  204. newCallback) {
  205. try {
  206. this.statisticsCallback = newCallback;
  207. } on PlatformException catch (e) {
  208. print("Plugin error: ${e.message}");
  209. }
  210. }
  211. /// Returns the last received statistics data stored in bitrate, size, speed, time, videoFps, videoFrameNumber and
  212. /// videoQuality fields
  213. Future<Map<dynamic, dynamic>> getLastReceivedStatistics() async {
  214. try {
  215. final Map<dynamic, dynamic> result =
  216. await _methodChannel.invokeMethod('getLastReceivedStatistics');
  217. return result;
  218. } on PlatformException catch (e) {
  219. print("Plugin error: ${e.message}");
  220. return null;
  221. }
  222. }
  223. /// Resets last received statistics. It is recommended to call it before starting a new execution.
  224. Future<void> resetStatistics() async {
  225. try {
  226. await _methodChannel.invokeMethod('resetStatistics');
  227. } on PlatformException catch (e) {
  228. print("Plugin error: ${e.message}");
  229. }
  230. }
  231. /// Sets and overrides fontconfig configuration directory.
  232. Future<void> setFontconfigConfigurationPath(String path) async {
  233. try {
  234. await _methodChannel
  235. .invokeMethod('setFontconfigConfigurationPath', {'path': path});
  236. } on PlatformException catch (e) {
  237. print("Plugin error: ${e.message}");
  238. }
  239. }
  240. /// Registers fonts inside the given [fontDirectory], so they are available to use in FFmpeg filters.
  241. Future<void> setFontDirectory(
  242. String fontDirectory, Map<String, String> fontNameMap) async {
  243. var parameters;
  244. if (fontNameMap == null) {
  245. parameters = {'fontDirectory': fontDirectory};
  246. } else {
  247. parameters = {'fontDirectory': fontDirectory, 'fontNameMap': fontNameMap};
  248. }
  249. try {
  250. await _methodChannel.invokeMethod('setFontDirectory', parameters);
  251. } on PlatformException catch (e) {
  252. print("Plugin error: ${e.message}");
  253. }
  254. }
  255. /// Returns FlutterFFmpeg package name.
  256. Future<String> getPackageName() async {
  257. try {
  258. final Map<dynamic, dynamic> result =
  259. await _methodChannel.invokeMethod('getPackageName');
  260. return result['packageName'];
  261. } on PlatformException catch (e) {
  262. print("Plugin error: ${e.message}");
  263. return null;
  264. }
  265. }
  266. /// Returns supported external libraries.
  267. Future<List<dynamic>> getExternalLibraries() async {
  268. try {
  269. final List<dynamic> result =
  270. await _methodChannel.invokeMethod('getExternalLibraries');
  271. return result;
  272. } on PlatformException catch (e) {
  273. print("Plugin error: ${e.message}");
  274. return null;
  275. }
  276. }
  277. /// Returns return code of last executed command.
  278. Future<int> getLastReturnCode() async {
  279. try {
  280. final Map<dynamic, dynamic> result =
  281. await _methodChannel.invokeMethod('getLastReturnCode');
  282. return result['lastRc'];
  283. } on PlatformException catch (e) {
  284. print("Plugin error: ${e.message}");
  285. return -1;
  286. }
  287. }
  288. /// Returns log output of last executed command. Please note that disabling redirection using
  289. /// 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.
  290. /// [disableRedirection()] method also disables this functionality.
  291. Future<String> getLastCommandOutput() async {
  292. try {
  293. final Map<dynamic, dynamic> result =
  294. await _methodChannel.invokeMethod('getLastCommandOutput');
  295. return result['lastCommandOutput'];
  296. } on PlatformException catch (e) {
  297. print("Plugin error: ${e.message}");
  298. return null;
  299. }
  300. }
  301. /// Creates a new FFmpeg pipe and returns its path.
  302. Future<String> registerNewFFmpegPipe() async {
  303. try {
  304. final Map<dynamic, dynamic> result =
  305. await _methodChannel.invokeMethod('registerNewFFmpegPipe');
  306. return result['pipe'];
  307. } on PlatformException catch (e) {
  308. print("Plugin error: ${e.message}");
  309. return null;
  310. }
  311. }
  312. }
  313. class FlutterFFmpeg {
  314. static const MethodChannel _methodChannel =
  315. const MethodChannel('flutter_ffmpeg');
  316. /// Executes FFmpeg with [commandArguments] provided.
  317. Future<int> executeWithArguments(List<String> arguments) async {
  318. try {
  319. final Map<dynamic, dynamic> result = await _methodChannel
  320. .invokeMethod('executeFFmpegWithArguments', {'arguments': arguments});
  321. return result['rc'];
  322. } on PlatformException catch (e) {
  323. print("Plugin error: ${e.message}");
  324. return -1;
  325. }
  326. }
  327. /// Executes FFmpeg [command] provided.
  328. Future<int> execute(String command) async {
  329. try {
  330. final Map<dynamic, dynamic> result = await _methodChannel.invokeMethod(
  331. 'executeFFmpegWithArguments',
  332. {'arguments': FlutterFFmpeg.parseArguments(command)});
  333. return result['rc'];
  334. } on PlatformException catch (e) {
  335. print("Plugin error: ${e.message}");
  336. return -1;
  337. }
  338. }
  339. /// Cancels an ongoing operation.
  340. Future<void> cancel() async {
  341. try {
  342. await _methodChannel.invokeMethod('cancel');
  343. } on PlatformException catch (e) {
  344. print("Plugin error: ${e.message}");
  345. }
  346. }
  347. /// Parses the given [command] into arguments.
  348. static List<String> parseArguments(String command) {
  349. List<String> argumentList = new List();
  350. StringBuffer currentArgument = new StringBuffer();
  351. bool singleQuoteStarted = false;
  352. bool doubleQuoteStarted = false;
  353. for (int i = 0; i < command.length; i++) {
  354. var previousChar;
  355. if (i > 0) {
  356. previousChar = command.codeUnitAt(i - 1);
  357. } else {
  358. previousChar = null;
  359. }
  360. var currentChar = command.codeUnitAt(i);
  361. if (currentChar == ' '.codeUnitAt(0)) {
  362. if (singleQuoteStarted || doubleQuoteStarted) {
  363. currentArgument.write(String.fromCharCode(currentChar));
  364. } else if (currentArgument.length > 0) {
  365. argumentList.add(currentArgument.toString());
  366. currentArgument = new StringBuffer();
  367. }
  368. } else if (currentChar == '\''.codeUnitAt(0) &&
  369. (previousChar == null || previousChar != '\\'.codeUnitAt(0))) {
  370. if (singleQuoteStarted) {
  371. singleQuoteStarted = false;
  372. } else if (doubleQuoteStarted) {
  373. currentArgument.write(String.fromCharCode(currentChar));
  374. } else {
  375. singleQuoteStarted = true;
  376. }
  377. } else if (currentChar == '\"'.codeUnitAt(0) &&
  378. (previousChar == null || previousChar != '\\'.codeUnitAt(0))) {
  379. if (doubleQuoteStarted) {
  380. doubleQuoteStarted = false;
  381. } else if (singleQuoteStarted) {
  382. currentArgument.write(String.fromCharCode(currentChar));
  383. } else {
  384. doubleQuoteStarted = true;
  385. }
  386. } else {
  387. currentArgument.write(String.fromCharCode(currentChar));
  388. }
  389. }
  390. if (currentArgument.length > 0) {
  391. argumentList.add(currentArgument.toString());
  392. }
  393. return argumentList;
  394. }
  395. }
  396. class FlutterFFprobe {
  397. static const MethodChannel _methodChannel =
  398. const MethodChannel('flutter_ffmpeg');
  399. /// Executes FFprobe with [commandArguments] provided.
  400. Future<int> executeWithArguments(List<String> arguments) async {
  401. try {
  402. final Map<dynamic, dynamic> result = await _methodChannel.invokeMethod(
  403. 'executeFFprobeWithArguments', {'arguments': arguments});
  404. return result['rc'];
  405. } on PlatformException catch (e) {
  406. print("Plugin error: ${e.message}");
  407. return -1;
  408. }
  409. }
  410. /// Executes FFprobe [command] provided.
  411. Future<int> execute(String command) async {
  412. try {
  413. final Map<dynamic, dynamic> result = await _methodChannel.invokeMethod(
  414. 'executeFFprobeWithArguments',
  415. {'arguments': FlutterFFmpeg.parseArguments(command)});
  416. return result['rc'];
  417. } on PlatformException catch (e) {
  418. print("Plugin error: ${e.message}");
  419. return -1;
  420. }
  421. }
  422. /// Returns media information for given [path]
  423. Future<Map<dynamic, dynamic>> getMediaInformation(String path) async {
  424. try {
  425. return await _methodChannel
  426. .invokeMethod('getMediaInformation', {'path': path});
  427. } on PlatformException catch (e) {
  428. print("Plugin error: ${e.message}");
  429. return null;
  430. }
  431. }
  432. }