flutter_ffmpeg_example.dart 30 KB

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