flutter_ffmpeg_example.dart 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:flutter_ffmpeg/flutter_ffmpeg.dart';
  6. import 'package:flutter_ffmpeg/log_level.dart';
  7. import 'package:path/path.dart';
  8. import 'package:path_provider/path_provider.dart';
  9. void main() => runApp(FlutterFFmpegTestApp());
  10. class FlutterFFmpegTestApp extends StatelessWidget {
  11. @override
  12. Widget build(BuildContext context) {
  13. return MaterialApp(
  14. theme: ThemeData(
  15. primaryColor: Color(0xFFF46842),
  16. ),
  17. home: MainPage(),
  18. );
  19. }
  20. }
  21. class MainPage extends StatefulWidget {
  22. @override
  23. FlutterFFmpegTestAppState createState() => new FlutterFFmpegTestAppState();
  24. }
  25. class DecoratedTabBar extends StatelessWidget implements PreferredSizeWidget {
  26. DecoratedTabBar({@required this.tabBar, @required this.decoration});
  27. final TabBar tabBar;
  28. final BoxDecoration decoration;
  29. @override
  30. Size get preferredSize => tabBar.preferredSize;
  31. @override
  32. Widget build(BuildContext context) {
  33. return Stack(
  34. children: [
  35. Positioned.fill(child: Container(decoration: decoration)),
  36. tabBar,
  37. ],
  38. );
  39. }
  40. }
  41. class VideoUtil {
  42. static Future<Directory> get tempDirectory async {
  43. return await getTemporaryDirectory();
  44. }
  45. static Future<File> copyFileAssets(String assetName, String localName) async {
  46. final ByteData assetByteData = await rootBundle.load(assetName);
  47. final List<int> byteList = assetByteData.buffer.asUint8List(assetByteData.offsetInBytes, assetByteData.lengthInBytes);
  48. final String fullTemporaryPath = join((await tempDirectory).path, localName);
  49. return new File(fullTemporaryPath).writeAsBytes(byteList, mode: FileMode.writeOnly, flush: true);
  50. }
  51. static Future<String> assetPath(String assetName) async {
  52. return join((await tempDirectory).path, assetName);
  53. }
  54. static String generateEncodeVideoScript(String image1Path, String image2Path, String image3Path, String videoFilePath, String videoCodec, String customOptions) {
  55. return "-hide_banner -y -loop 1 -i '" +
  56. image1Path +
  57. "' " +
  58. "-loop 1 -i \"" +
  59. image2Path +
  60. "\" " +
  61. "-loop 1 -i \"" +
  62. image3Path +
  63. "\" " +
  64. "-filter_complex " +
  65. "\"[0:v]setpts=PTS-STARTPTS,scale=w='if(gte(iw/ih,640/427),min(iw,640),-1)':h='if(gte(iw/ih,640/427),-1,min(ih,427))',scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=sar=1/1,split=2[stream1out1][stream1out2];" +
  66. "[1:v]setpts=PTS-STARTPTS,scale=w='if(gte(iw/ih,640/427),min(iw,640),-1)':h='if(gte(iw/ih,640/427),-1,min(ih,427))',scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=sar=1/1,split=2[stream2out1][stream2out2];" +
  67. "[2:v]setpts=PTS-STARTPTS,scale=w='if(gte(iw/ih,640/427),min(iw,640),-1)':h='if(gte(iw/ih,640/427),-1,min(ih,427))',scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=sar=1/1,split=2[stream3out1][stream3out2];" +
  68. "[stream1out1]pad=width=640:height=427:x=(640-iw)/2:y=(427-ih)/2:color=#00000000,trim=duration=3,select=lte(n\\,90)[stream1overlaid];" +
  69. "[stream1out2]pad=width=640:height=427:x=(640-iw)/2:y=(427-ih)/2:color=#00000000,trim=duration=1,select=lte(n\\,30)[stream1ending];" +
  70. "[stream2out1]pad=width=640:height=427:x=(640-iw)/2:y=(427-ih)/2:color=#00000000,trim=duration=2,select=lte(n\\,60)[stream2overlaid];" +
  71. "[stream2out2]pad=width=640:height=427:x=(640-iw)/2:y=(427-ih)/2:color=#00000000,trim=duration=1,select=lte(n\\,30),split=2[stream2starting][stream2ending];" +
  72. "[stream3out1]pad=width=640:height=427:x=(640-iw)/2:y=(427-ih)/2:color=#00000000,trim=duration=2,select=lte(n\\,60)[stream3overlaid];" +
  73. "[stream3out2]pad=width=640:height=427:x=(640-iw)/2:y=(427-ih)/2:color=#00000000,trim=duration=1,select=lte(n\\,30)[stream3starting];" +
  74. "[stream2starting][stream1ending]blend=all_expr='if(gte(X,(W/2)*T/1)*lte(X,W-(W/2)*T/1),B,A)':shortest=1[stream2blended];" +
  75. "[stream3starting][stream2ending]blend=all_expr='if(gte(X,(W/2)*T/1)*lte(X,W-(W/2)*T/1),B,A)':shortest=1[stream3blended];" +
  76. "[stream1overlaid][stream2blended][stream2overlaid][stream3blended][stream3overlaid]concat=n=5:v=1:a=0,scale=w=640:h=424,format=yuv420p[video]\"" +
  77. " -map [video] -vsync 2 -async 1 " +
  78. customOptions +
  79. "-c:v " +
  80. videoCodec +
  81. " -r 30 " +
  82. videoFilePath;
  83. }
  84. }
  85. class FlutterFFmpegTestAppState extends State<MainPage> with TickerProviderStateMixin {
  86. static const String ASSET_1 = "1.jpg";
  87. static const String ASSET_2 = "2.jpg";
  88. static const String ASSET_3 = "3.jpg";
  89. final FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();
  90. TextEditingController _commandController;
  91. TabController _controller;
  92. String _commandOutput;
  93. String _encodeOutput;
  94. String _currentCodec;
  95. List<DropdownMenuItem<String>> _codecDropDownMenuItems;
  96. @override
  97. void initState() {
  98. super.initState();
  99. _commandController = TextEditingController();
  100. _controller = TabController(length: 2, vsync: this);
  101. _commandOutput = "";
  102. _encodeOutput = "";
  103. _codecDropDownMenuItems = _getCodecDropDownMenuItems();
  104. _currentCodec = _codecDropDownMenuItems[0].value;
  105. startupTests();
  106. prepareAssets();
  107. }
  108. void startupTests() {
  109. getFFmpegVersion().then((version) => print("FFmpeg version: $version"));
  110. getPlatform().then((platform) => print("Platform: $platform"));
  111. getLogLevel().then((level) => print("Old log level: " + LogLevel.levelToString(level)));
  112. setLogLevel(LogLevel.AV_LOG_INFO);
  113. getLogLevel().then((level) => print("New log level: " + LogLevel.levelToString(level)));
  114. getPackageName().then((packageName) => print("Package name: $packageName"));
  115. getExternalLibraries().then((packageList) {
  116. packageList.forEach((value) => print("External library: $value"));
  117. });
  118. }
  119. void prepareAssets() {
  120. VideoUtil.copyFileAssets('assets/pyramid.jpg', ASSET_1).then((path) => print('Loaded asset $path.'));
  121. VideoUtil.copyFileAssets('assets/colosseum.jpg', ASSET_2).then((path) => print('Loaded asset $path.'));
  122. VideoUtil.copyFileAssets('assets/tajmahal.jpg', ASSET_3).then((path) => print('Loaded asset $path.'));
  123. }
  124. void testParseArguments() {
  125. testParseSimpleCommand();
  126. testParseSingleQuotesInCommand();
  127. testParseDoubleQuotesInCommand();
  128. testParseDoubleQuotesAndEscapesInCommand();
  129. }
  130. void testRunCommand() {
  131. getLastReturnCode().then((rc) => print("Last rc: $rc"));
  132. getLastCommandOutput().then((output) => debugPrint("Last command output: \"$output\"", wrapWidth: 1024));
  133. print("Testing ParseArguments.");
  134. testParseArguments();
  135. registerNewFFmpegPipe().then((path) => print("New FFmpeg pipe: $path"));
  136. print("Testing COMMAND.");
  137. // ENABLE LOG CALLBACK ON EACH CALL
  138. _flutterFFmpeg.enableLogCallback(commandOutputLogCallback);
  139. _flutterFFmpeg.enableStatisticsCallback(statisticsCallback);
  140. // CLEAR OUTPUT ON EACH EXECUTION
  141. _commandOutput = "";
  142. // COMMENT OPTIONAL TESTS
  143. // VideoUtil.tempDirectory.then((tempDirectory) {
  144. // Map<String, String> mapNameMap = new Map();
  145. // mapNameMap["my_custom_font"] = "my custom font";
  146. // setFontDirectory(tempDirectory.path, null);
  147. // });
  148. VideoUtil.tempDirectory.then((tempDirectory) {
  149. setFontconfigConfigurationPath(tempDirectory.path);
  150. });
  151. // disableRedirection();
  152. // disableLogs();
  153. // enableLogs();
  154. execute(_commandController.text).then((rc) => print("FFmpeg process exited with rc $rc"));
  155. // executeWithArguments(_commandController.text.split(" ")).then((rc) => print("FFmpeg process exited with rc $rc"));
  156. setState(() {});
  157. }
  158. void testGetMediaInformation(String mediaPath) {
  159. print("Testing Get Media Information.");
  160. // ENABLE LOG CALLBACK ON EACH CALL
  161. _flutterFFmpeg.enableLogCallback(commandOutputLogCallback);
  162. _flutterFFmpeg.enableStatisticsCallback(null);
  163. // CLEAR OUTPUT ON EACH EXECUTION
  164. _commandOutput = "";
  165. VideoUtil.assetPath(mediaPath).then((image1Path) {
  166. getMediaInformation(image1Path).then((info) {
  167. print('Media Information');
  168. print('Path: ${info['path']}');
  169. print('Format: ${info['format']}');
  170. print('Duration: ${info['duration']}');
  171. print('Start time: ${info['startTime']}');
  172. print('Bitrate: ${info['bitrate']}');
  173. if (info['streams'] != null) {
  174. final streamsInfoArray = info['streams'];
  175. if (streamsInfoArray.length > 0) {
  176. for (var streamsInfo in streamsInfoArray) {
  177. print('Stream id: ${streamsInfo['index']}');
  178. print('Stream type: ${streamsInfo['type']}');
  179. print('Stream codec: ${streamsInfo['codec']}');
  180. print('Stream full codec: ${streamsInfo['fullCodec']}');
  181. print('Stream format: ${streamsInfo['format']}');
  182. print('Stream full format: ${streamsInfo['fullFormat']}');
  183. print('Stream width: ${streamsInfo['width']}');
  184. print('Stream height: ${streamsInfo['height']}');
  185. print('Stream bitrate: ${streamsInfo['bitrate']}');
  186. print('Stream sample rate: ${streamsInfo['sampleRate']}');
  187. print('Stream sample format: ${streamsInfo['sampleFormat']}');
  188. print('Stream channel layout: ${streamsInfo['channelLayout']}');
  189. print('Stream sar: ${streamsInfo['sampleAspectRatio']}');
  190. print('Stream dar: ${streamsInfo['displayAspectRatio']}');
  191. print('Stream average frame rate: ${streamsInfo['averageFrameRate']}');
  192. print('Stream real frame rate: ${streamsInfo['realFrameRate']}');
  193. print('Stream time base: ${streamsInfo['timeBase']}');
  194. print('Stream codec time base: ${streamsInfo['codecTimeBase']}');
  195. final metadataMap = streamsInfo['metadata'];
  196. if (metadataMap != null) {
  197. print('Stream metadata encoder: ${metadataMap['encoder']}');
  198. print('Stream metadata rotate: ${metadataMap['rotate']}');
  199. print('Stream metadata creation time: ${metadataMap['creation_time']}');
  200. print('Stream metadata handler name: ${metadataMap['handler_name']}');
  201. }
  202. final sideDataMap = streamsInfo['sidedata'];
  203. if (sideDataMap != null) {
  204. print('Stream side data displaymatrix: ${sideDataMap['displaymatrix']}');
  205. }
  206. }
  207. }
  208. }
  209. });
  210. });
  211. setState(() {});
  212. }
  213. void testEncodeVideo() {
  214. print("Testing VIDEO.");
  215. // ENABLE LOG CALLBACK ON EACH CALL
  216. _flutterFFmpeg.enableLogCallback(encodeOutputLogCallback);
  217. _flutterFFmpeg.enableStatisticsCallback(statisticsCallback);
  218. // CLEAR OUTPUT ON EACH EXECUTION
  219. _encodeOutput = "";
  220. disableStatistics();
  221. enableStatistics();
  222. VideoUtil.assetPath(ASSET_1).then((image1Path) {
  223. VideoUtil.assetPath(ASSET_2).then((image2Path) {
  224. VideoUtil.assetPath(ASSET_3).then((image3Path) {
  225. final String videoPath = getVideoPath();
  226. final String customOptions = getCustomEncodingOptions();
  227. final String ffmpegCodec = getFFmpegCodecName();
  228. VideoUtil.assetPath(videoPath).then((fullVideoPath) {
  229. execute(VideoUtil.generateEncodeVideoScript(image1Path, image2Path, image3Path, fullVideoPath, ffmpegCodec, customOptions)).then((rc) {
  230. if (rc == 0) {
  231. getLastCommandOutput().then((output) => debugPrint("Last command output: \"$output\"", wrapWidth: 1024));
  232. }
  233. });
  234. // resetStatistics();
  235. getLastReceivedStatistics().then((lastStatistics) {
  236. if (lastStatistics == null) {
  237. print('No last statistics');
  238. } else {
  239. print('Last statistics');
  240. int time = lastStatistics['time'];
  241. int size = lastStatistics['size'];
  242. double bitrate = _doublePrecision(lastStatistics['bitrate'], 2);
  243. double speed = _doublePrecision(lastStatistics['speed'], 2);
  244. int videoFrameNumber = lastStatistics['videoFrameNumber'];
  245. double videoQuality = _doublePrecision(lastStatistics['videoQuality'], 2);
  246. double videoFps = _doublePrecision(lastStatistics['videoFps'], 2);
  247. statisticsCallback(time, size, bitrate, speed, videoFrameNumber, videoQuality, videoFps);
  248. }
  249. });
  250. });
  251. });
  252. });
  253. });
  254. setState(() {});
  255. }
  256. void commandOutputLogCallback(int level, String message) {
  257. _commandOutput += message;
  258. setState(() {});
  259. }
  260. void encodeOutputLogCallback(int level, String message) {
  261. _encodeOutput += message;
  262. setState(() {});
  263. }
  264. void statisticsCallback(int time, int size, double bitrate, double speed, int videoFrameNumber, double videoQuality, double videoFps) {
  265. print("Statistics: time: $time, size: $size, bitrate: $bitrate, speed: $speed, videoFrameNumber: $videoFrameNumber, videoQuality: $videoQuality, videoFps: $videoFps");
  266. }
  267. Future<String> getFFmpegVersion() async {
  268. return await _flutterFFmpeg.getFFmpegVersion();
  269. }
  270. Future<String> getPlatform() async {
  271. return await _flutterFFmpeg.getPlatform();
  272. }
  273. Future<int> executeWithArguments(List arguments) async {
  274. return await _flutterFFmpeg.executeWithArguments(arguments);
  275. }
  276. Future<int> execute(String command) async {
  277. return await _flutterFFmpeg.execute(command);
  278. }
  279. Future<void> cancel() async {
  280. return await _flutterFFmpeg.cancel();
  281. }
  282. Future<void> disableRedirection() async {
  283. return await _flutterFFmpeg.disableRedirection();
  284. }
  285. Future<int> getLogLevel() async {
  286. return await _flutterFFmpeg.getLogLevel();
  287. }
  288. Future<void> setLogLevel(int logLevel) async {
  289. return await _flutterFFmpeg.setLogLevel(logLevel);
  290. }
  291. Future<void> enableLogs() async {
  292. return await _flutterFFmpeg.enableLogs();
  293. }
  294. Future<void> disableLogs() async {
  295. return await _flutterFFmpeg.disableLogs();
  296. }
  297. Future<void> enableStatistics() async {
  298. return await _flutterFFmpeg.enableStatistics();
  299. }
  300. Future<void> disableStatistics() async {
  301. return await _flutterFFmpeg.disableStatistics();
  302. }
  303. Future<Map<dynamic, dynamic>> getLastReceivedStatistics() async {
  304. return await _flutterFFmpeg.getLastReceivedStatistics();
  305. }
  306. Future<void> resetStatistics() async {
  307. return await _flutterFFmpeg.resetStatistics();
  308. }
  309. Future<void> setFontconfigConfigurationPath(String path) async {
  310. return await _flutterFFmpeg.setFontconfigConfigurationPath(path);
  311. }
  312. Future<void> setFontDirectory(String fontDirectory, Map<String, String> fontNameMap) async {
  313. return await _flutterFFmpeg.setFontDirectory(fontDirectory, fontNameMap);
  314. }
  315. Future<String> getPackageName() async {
  316. return await _flutterFFmpeg.getPackageName();
  317. }
  318. Future<List<dynamic>> getExternalLibraries() async {
  319. return await _flutterFFmpeg.getExternalLibraries();
  320. }
  321. Future<int> getLastReturnCode() async {
  322. return await _flutterFFmpeg.getLastReturnCode();
  323. }
  324. Future<String> getLastCommandOutput() async {
  325. return await _flutterFFmpeg.getLastCommandOutput();
  326. }
  327. Future<Map<dynamic, dynamic>> getMediaInformation(String path) async {
  328. return await _flutterFFmpeg.getMediaInformation(path);
  329. }
  330. Future<String> registerNewFFmpegPipe() async {
  331. return await _flutterFFmpeg.registerNewFFmpegPipe();
  332. }
  333. void _changedCodec(String selectedCodec) {
  334. setState(() {
  335. _currentCodec = selectedCodec;
  336. });
  337. }
  338. String getFFmpegCodecName() {
  339. String ffmpegCodec = _currentCodec;
  340. // VIDEO CODEC MENU HAS BASIC NAMES, FFMPEG NEEDS LONGER LIBRARY NAMES.
  341. if (ffmpegCodec == "x264") {
  342. ffmpegCodec = "libx264";
  343. } else if (ffmpegCodec == "x265") {
  344. ffmpegCodec = "libx265";
  345. } else if (ffmpegCodec == "xvid") {
  346. ffmpegCodec = "libxvid";
  347. } else if (ffmpegCodec == "vp8") {
  348. ffmpegCodec = "libvpx";
  349. } else if (ffmpegCodec == "vp9") {
  350. ffmpegCodec = "libvpx-vp9";
  351. }
  352. return ffmpegCodec;
  353. }
  354. String getVideoPath() {
  355. String ffmpegCodec = _currentCodec;
  356. String videoPath;
  357. if ((ffmpegCodec == "vp8") || (ffmpegCodec == "vp9")) {
  358. videoPath = "video.webm";
  359. } else {
  360. // mpeg4, x264, x265, xvid
  361. videoPath = "video.mp4";
  362. }
  363. return videoPath;
  364. }
  365. String getCustomEncodingOptions() {
  366. String videoCodec = _currentCodec;
  367. if (videoCodec == "x265") {
  368. return "-crf 28 -preset fast ";
  369. } else if (videoCodec == "vp8") {
  370. return "-b:v 1M -crf 10 ";
  371. } else if (videoCodec == "vp9") {
  372. return "-b:v 2M ";
  373. } else {
  374. return "";
  375. }
  376. }
  377. List<DropdownMenuItem<String>> _getCodecDropDownMenuItems() {
  378. List<DropdownMenuItem<String>> items = new List();
  379. items.add(new DropdownMenuItem(value: "mpeg4", child: new Text("mpeg4")));
  380. items.add(new DropdownMenuItem(value: "x264", child: new Text("x264")));
  381. items.add(new DropdownMenuItem(value: "x265", child: new Text("x265")));
  382. items.add(new DropdownMenuItem(value: "xvid", child: new Text("xvid")));
  383. items.add(new DropdownMenuItem(value: "vp8", child: new Text("vp8")));
  384. items.add(new DropdownMenuItem(value: "vp9", child: new Text("vp9")));
  385. return items;
  386. }
  387. double _doublePrecision(double value, int precision) {
  388. if (value == null) {
  389. return 0;
  390. } else {
  391. return num.parse(value.toStringAsFixed(precision));
  392. }
  393. }
  394. @override
  395. Widget build(BuildContext context) {
  396. return Scaffold(
  397. appBar: AppBar(
  398. title: Text('FlutterFFmpeg Test'),
  399. centerTitle: true,
  400. ),
  401. bottomNavigationBar: Material(
  402. child: DecoratedTabBar(
  403. tabBar: TabBar(
  404. tabs: <Tab>[
  405. Tab(text: "COMMAND"),
  406. Tab(
  407. text: "VIDEO",
  408. )
  409. ],
  410. controller: _controller,
  411. labelColor: Color(0xFF1e90ff),
  412. unselectedLabelColor: Color(0xFF808080),
  413. ),
  414. decoration: BoxDecoration(
  415. border: Border(
  416. top: BorderSide(
  417. color: Color(0xFF808080),
  418. width: 1.0,
  419. ),
  420. bottom: BorderSide(
  421. width: 0.0,
  422. ),
  423. ),
  424. ),
  425. ),
  426. ),
  427. body: TabBarView(
  428. children: <Widget>[
  429. Column(
  430. crossAxisAlignment: CrossAxisAlignment.center,
  431. children: <Widget>[
  432. Container(
  433. padding: const EdgeInsets.fromLTRB(20, 40, 20, 40),
  434. child: TextField(
  435. controller: _commandController,
  436. decoration: InputDecoration(
  437. border: const OutlineInputBorder(
  438. borderSide: const BorderSide(color: Color(0xFF3498DB)),
  439. borderRadius: const BorderRadius.all(
  440. const Radius.circular(5),
  441. ),
  442. ),
  443. focusedBorder: const OutlineInputBorder(
  444. borderSide: const BorderSide(color: Color(0xFF3498DB)),
  445. borderRadius: const BorderRadius.all(
  446. const Radius.circular(5),
  447. ),
  448. ),
  449. enabledBorder: const OutlineInputBorder(
  450. borderSide: const BorderSide(color: Color(0xFF3498DB)),
  451. borderRadius: const BorderRadius.all(
  452. const Radius.circular(5),
  453. ),
  454. ),
  455. contentPadding: EdgeInsets.fromLTRB(8, 12, 8, 12),
  456. hintStyle: new TextStyle(fontSize: 14, color: Colors.grey[400]),
  457. hintText: "Enter command"),
  458. style: new TextStyle(fontSize: 14, color: Colors.black),
  459. ),
  460. ),
  461. Container(
  462. padding: const EdgeInsets.only(bottom: 20),
  463. child: new InkWell(
  464. onTap: () => testRunCommand(),
  465. child: new Container(
  466. width: 100,
  467. height: 38,
  468. decoration: new BoxDecoration(
  469. color: Color(0xFF2ECC71),
  470. borderRadius: new BorderRadius.circular(5),
  471. ),
  472. child: new Center(
  473. child: new Text(
  474. 'RUN',
  475. style: new TextStyle(fontSize: 14.0, fontWeight: FontWeight.bold, color: Colors.white),
  476. ),
  477. ),
  478. ),
  479. ),
  480. ),
  481. Expanded(
  482. child: Container(
  483. alignment: Alignment(-1.0, -1.0),
  484. margin: EdgeInsets.all(20.0),
  485. padding: EdgeInsets.all(4.0),
  486. decoration: new BoxDecoration(borderRadius: BorderRadius.all(new Radius.circular(5)), color: Color(0xFFF1C40F)),
  487. child: SingleChildScrollView(reverse: true, child: Text(_commandOutput))),
  488. )
  489. ],
  490. ),
  491. Column(
  492. crossAxisAlignment: CrossAxisAlignment.center,
  493. children: <Widget>[
  494. Container(
  495. padding: const EdgeInsets.fromLTRB(20, 40, 20, 40),
  496. child: Container(
  497. width: 200,
  498. alignment: Alignment(0.0, 0.0),
  499. decoration: BoxDecoration(color: Color.fromRGBO(155, 89, 182, 1.0), borderRadius: BorderRadius.circular(5)),
  500. child: DropdownButtonHideUnderline(
  501. child: DropdownButton(
  502. style: new TextStyle(
  503. fontSize: 14,
  504. color: Colors.black,
  505. ),
  506. value: _currentCodec,
  507. items: _codecDropDownMenuItems,
  508. onChanged: _changedCodec,
  509. iconSize: 0,
  510. isExpanded: false,
  511. )),
  512. )),
  513. Container(
  514. padding: const EdgeInsets.only(bottom: 20),
  515. child: new InkWell(
  516. onTap: () => testEncodeVideo(),
  517. child: new Container(
  518. width: 100,
  519. height: 38,
  520. decoration: new BoxDecoration(
  521. color: Color(0xFF2ECC71),
  522. borderRadius: new BorderRadius.circular(5),
  523. ),
  524. child: new Center(
  525. child: new Text(
  526. 'ENCODE',
  527. style: new TextStyle(fontSize: 14.0, fontWeight: FontWeight.bold, color: Colors.white),
  528. ),
  529. ),
  530. ),
  531. ),
  532. ),
  533. Expanded(
  534. child: Container(
  535. alignment: Alignment(-1.0, -1.0),
  536. margin: EdgeInsets.all(20.0),
  537. padding: EdgeInsets.all(4.0),
  538. decoration: new BoxDecoration(borderRadius: BorderRadius.all(new Radius.circular(5)), color: Color(0xFFF1C40F)),
  539. child: SingleChildScrollView(reverse: true, child: Text(_encodeOutput))),
  540. )
  541. ],
  542. ),
  543. ],
  544. controller: _controller,
  545. ));
  546. }
  547. @override
  548. void dispose() {
  549. super.dispose();
  550. _commandController.dispose();
  551. }
  552. void testParseSimpleCommand() {
  553. var argumentArray = _flutterFFmpeg.parseArguments("-hide_banner -loop 1 -i file.jpg -filter_complex [0:v]setpts=PTS-STARTPTS[video] -map [video] -vsync 2 -async 1 video.mp4");
  554. assert(argumentArray != null);
  555. assert(argumentArray.length == 14);
  556. assert("-hide_banner" == argumentArray[0]);
  557. assert("-loop" == argumentArray[1]);
  558. assert("1" == argumentArray[2]);
  559. assert("-i" == argumentArray[3]);
  560. assert("file.jpg" == argumentArray[4]);
  561. assert("-filter_complex" == argumentArray[5]);
  562. assert("[0:v]setpts=PTS-STARTPTS[video]" == argumentArray[6]);
  563. assert("-map" == argumentArray[7]);
  564. assert("[video]" == argumentArray[8]);
  565. assert("-vsync" == argumentArray[9]);
  566. assert("2" == argumentArray[10]);
  567. assert("-async" == argumentArray[11]);
  568. assert("1" == argumentArray[12]);
  569. assert("video.mp4" == argumentArray[13]);
  570. }
  571. void testParseSingleQuotesInCommand() {
  572. var argumentArray = _flutterFFmpeg.parseArguments("-loop 1 'file one.jpg' -filter_complex '[0:v]setpts=PTS-STARTPTS[video]' -map [video] video.mp4 ");
  573. assert(argumentArray != null);
  574. assert(argumentArray.length == 8);
  575. assert("-loop" == argumentArray[0]);
  576. assert("1" == argumentArray[1]);
  577. assert("file one.jpg" == argumentArray[2]);
  578. assert("-filter_complex" == argumentArray[3]);
  579. assert("[0:v]setpts=PTS-STARTPTS[video]" == argumentArray[4]);
  580. assert("-map" == argumentArray[5]);
  581. assert("[video]" == argumentArray[6]);
  582. assert("video.mp4" == argumentArray[7]);
  583. }
  584. void testParseDoubleQuotesInCommand() {
  585. var argumentArray = _flutterFFmpeg.parseArguments("-loop 1 \"file one.jpg\" -filter_complex \"[0:v]setpts=PTS-STARTPTS[video]\" -map [video] video.mp4 ");
  586. assert(argumentArray != null);
  587. assert(argumentArray.length == 8);
  588. assert("-loop" == argumentArray[0]);
  589. assert("1" == argumentArray[1]);
  590. assert("file one.jpg" == argumentArray[2]);
  591. assert("-filter_complex" == argumentArray[3]);
  592. assert("[0:v]setpts=PTS-STARTPTS[video]" == argumentArray[4]);
  593. assert("-map" == argumentArray[5]);
  594. assert("[video]" == argumentArray[6]);
  595. assert("video.mp4" == argumentArray[7]);
  596. argumentArray = _flutterFFmpeg.parseArguments(" -i file:///tmp/input.mp4 -vcodec libx264 -vf \"scale=1024:1024,pad=width=1024:height=1024:x=0:y=0:color=black\" -acodec copy -q:v 0 -q:a 0 video.mp4");
  597. assert(argumentArray != null);
  598. assert(argumentArray.length == 13);
  599. assert("-i" == argumentArray[0]);
  600. assert("file:///tmp/input.mp4" == argumentArray[1]);
  601. assert("-vcodec" == argumentArray[2]);
  602. assert("libx264" == argumentArray[3]);
  603. assert("-vf" == argumentArray[4]);
  604. assert("scale=1024:1024,pad=width=1024:height=1024:x=0:y=0:color=black" == argumentArray[5]);
  605. assert("-acodec" == argumentArray[6]);
  606. assert("copy" == argumentArray[7]);
  607. assert("-q:v" == argumentArray[8]);
  608. assert("0" == argumentArray[9]);
  609. assert("-q:a" == argumentArray[10]);
  610. assert("0" == argumentArray[11]);
  611. assert("video.mp4" == argumentArray[12]);
  612. }
  613. void testParseDoubleQuotesAndEscapesInCommand() {
  614. var argumentArray = _flutterFFmpeg.parseArguments(" -i file:///tmp/input.mp4 -vf \"subtitles=file:///tmp/subtitles.srt:force_style=\'FontSize=16,PrimaryColour=&HFFFFFF&\'\" -vcodec libx264 -acodec copy -q:v 0 -q:a 0 video.mp4");
  615. assert(argumentArray != null);
  616. assert(argumentArray.length == 13);
  617. assert("-i" == argumentArray[0]);
  618. assert("file:///tmp/input.mp4" == argumentArray[1]);
  619. assert("-vf" == argumentArray[2]);
  620. assert("subtitles=file:///tmp/subtitles.srt:force_style='FontSize=16,PrimaryColour=&HFFFFFF&'" == argumentArray[3]);
  621. assert("-vcodec" == argumentArray[4]);
  622. assert("libx264" == argumentArray[5]);
  623. assert("-acodec" == argumentArray[6]);
  624. assert("copy" == argumentArray[7]);
  625. assert("-q:v" == argumentArray[8]);
  626. assert("0" == argumentArray[9]);
  627. assert("-q:a" == argumentArray[10]);
  628. assert("0" == argumentArray[11]);
  629. assert("video.mp4" == argumentArray[12]);
  630. argumentArray = _flutterFFmpeg.parseArguments(" -i file:///tmp/input.mp4 -vf \"subtitles=file:///tmp/subtitles.srt:force_style=\\\"FontSize=16,PrimaryColour=&HFFFFFF&\\\"\" -vcodec libx264 -acodec copy -q:v 0 -q:a 0 video.mp4");
  631. assert(argumentArray != null);
  632. assert(argumentArray.length == 13);
  633. assert("-i" == argumentArray[0]);
  634. assert("file:///tmp/input.mp4" == argumentArray[1]);
  635. assert("-vf" == argumentArray[2]);
  636. assert("subtitles=file:///tmp/subtitles.srt:force_style=\\\"FontSize=16,PrimaryColour=&HFFFFFF&\\\"" == argumentArray[3]);
  637. assert("-vcodec" == argumentArray[4]);
  638. assert("libx264" == argumentArray[5]);
  639. assert("-acodec" == argumentArray[6]);
  640. assert("copy" == argumentArray[7]);
  641. assert("-q:v" == argumentArray[8]);
  642. assert("0" == argumentArray[9]);
  643. assert("-q:a" == argumentArray[10]);
  644. assert("0" == argumentArray[11]);
  645. assert("video.mp4" == argumentArray[12]);
  646. }
  647. }