├── 996LICENSE_CN ├── LICENSE ├── README.md ├── loadFFmpeg.properties ├── pom.xml └── src ├── cc └── eguid │ └── commandManager │ ├── CommandManager.java │ ├── CommandManagerImpl.java │ ├── callback │ ├── EventCallBack.java │ ├── EventCallBackType.java │ └── worker │ │ └── EventMsgNetWorker.java │ ├── commandbuidler │ ├── CommandAssembly.java │ ├── CommandAssemblyImpl.java │ ├── CommandBuidler.java │ ├── CommandBuidlerFactory.java │ └── DefaultCommandBuidler.java │ ├── config │ ├── ProgramConfig.java │ └── defaultFFmpegConfig.properties │ ├── data │ ├── CommandTasker.java │ ├── TaskDao.java │ ├── TaskDaoImpl.java │ └── TaskerEventMsg.java │ ├── handler │ ├── DefaultOutHandlerMethod.java │ ├── KeepAliveHandler.java │ ├── OutHandler.java │ ├── OutHandlerMethod.java │ ├── TaskHandler.java │ └── TaskHandlerImpl.java │ ├── test │ └── Test.java │ └── util │ ├── CommonUtil.java │ ├── ExecUtil.java │ ├── PropertiesUtil.java │ └── ReflectUtil.java ├── loadFFmpeg.properties └── readme.md /996LICENSE_CN: -------------------------------------------------------------------------------- 1 | 版权所有(c)2019-eguid (eguid@outlook.com) 2 | 3 | 反996许可证版本1.0 4 | 5 | 在符合下列条件的情况下,特此免费向任何得到本授权作品的副本(包括源代码、文件和/或相关内容,以 6 | 下统称为“授权作品”)的个人和法人实体授权:被授权个人或法人实体有权以任何目的处置授权作品,包括 7 | 但不限于使用、复制,修改,衍生利用、散布,发布和再许可: 8 | 9 | 1. 个人或法人实体必须在许可作品的每个再散布或衍生副本上包含以上版权声明和本许可证,不得自行修 10 | 改。 11 | 2. 个人或法人实体必须严格遵守与个人实际所在地或个人出生地或归化地、或法人实体注册地或经营地( 12 | 以较严格者为准)的司法管辖区所有适用的与劳动和就业相关法律、法规、规则和标准。如果该司法管辖区 13 | 没有此类法律、法规、规章和标准或其法律、法规、规章和标准不可执行,则个人或法人实体必须遵守国际 14 | 劳工标准的核心公约。 15 | 3. 个人或法人不得以任何方式诱导、暗示或强迫其全职或兼职员工或其独立承包人以口头或书面形式同意 16 | 直接或间接限制、削弱或放弃其所拥有的,受相关与劳动和就业有关的法律、法规、规则和标准保护的权利 17 | 或补救措施,无论该等书面或口头协议是否被该司法管辖区的法律所承认,该等个人或法人实体也不得以任 18 | 何方法限制其雇员或独立承包人向版权持有人或监督许可证合规情况的有关当局报告或投诉上述违反许可证 19 | 的行为的权利。 20 | 21 | 该授权作品是"按原样"提供,不做任何明示或暗示的保证,包括但不限于对适销性、特定用途适用性和非侵 22 | 权性的保证。在任何情况下,无论是在合同诉讼、侵权诉讼或其他诉讼中,版权持有人均不承担因本软件或 23 | 本软件的使用或其他交易而产生、引起或与之相关的任何索赔、损害或其他责任。 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2016-2019 eguid(eguid@outlook.com) 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![LICENSE](https://img.shields.io/badge/license-Anti%20996-blue.svg)](https://github.com/996icu/996.ICU/blob/master/LICENSE) 2 | [![LICENSE](https://camo.githubusercontent.com/f969af70fa6573766a11cb0a968fc82b069298f1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6c697a68696368616f2f6f6e652e737667)](https://github.com/eguid/FFCH4J/blob/master/LICENSE) 3 | # FFCH4J(原用名:FFmpegCommandHandler4java) 4 | FFCH4J项目全称:FFmpeg命令处理器,鉴于很多小伙伴们反馈原名太长,改为‘FFCH4J’ 5 | ## 说明 6 | java封装的提供ffmpeg命令执行、停止、查询功能的简单管理器 。 7 | FFCH4j不仅仅只支持ffmpeg命令,还支持执行多平台的命令行指令,不管是执行linux命令还是windows的命令行都是手到擒来(注意:本项目并未屏蔽某些敏感操作,比如rm -rf,当然这会产生一些风险,还请注意规避)。 8 | 除了保证命令行运行,还拥有独立的轻量级的保活线程来重启因为异常故障导致中断的任务。 9 | ## 特性 10 | 零依赖(不依赖任何第三方jar包,只需要java运行环境即可运行),完全接口化(所有内部组件都实现了完全接口化,开发人员可以方便的修改和扩展程序,比如自行实现持久层接口来替换默认的持久层) 11 | ## 版本说明 12 | 本次更新说明 13 | 1、配置文件增加保活线程和回调地址 14 | 2、新增命令行流式组装执行器 15 | 3、新增保活线程处理器,用于在后台保证任务可靠运行,如果任务中途中断,则立即强制重启任务,定制需要实现OutHandlerMethod接口并注入到命令行管理器 16 | 4、新增事件回调,将下个版本将整合进主程序中 17 | 18 | 上个版本更新说明 19 | 1、本次更新主要针对配置文件的加载优化,详情见下面的使用说明 20 | 初始化FFmpegManager时会自动查找loadFFmpeg.properties配置文件 21 | 配置文件的加载方式如下: 22 | (1)、javaSE项目会自动从项目根目录加载 23 | (2)、javaEE项目会自动从classes目录下加载(编写web项目的src目录下) 24 | (3)、如果上述位置都没有找到配置文件,会自动加载默认配置,默认的配置文件在config包下的defaultFFmpegConfig.properties中 25 | 26 | 2、支持自定义的消息输出 27 | 28 | 上个版本更新说明 29 | 3、增加一个String start(String id,String commond,boolean hasPath)接口,用于区分是否使用配置文件中的绝对路径,如果为false,请务必保证ffmpeg的路径可以正确加载 30 | 4、增加一个debug配置,用于判断是否输出关键位置的debug消息 31 | ## 基于 32 | 本项目基于jdk1.7开发,FFmpeg各版本支持的命令请参考[FFmpeg官方文档](http://ffmpeg.org/ffmpeg.html)
33 | ## 使用说明 34 | ```Java 35 | //18.12.02新版本创建方式 36 | CommandManager manager=new CommandManagerImpl(10); 37 | 38 | //老版本创建方式: 39 | FFmpegManager manager=new FFmpegManagerImpl(10); 40 | //当然也可以这样 41 | FFmpegManager manager=new FFmpegManagerImpl();//这样会从配置文件中读取size的值作为初始化参数 42 | //组装命令 43 | Map map = new HashMap(); 44 | map.put("appName", "test123"); 45 | map.put("input","rtsp://admin:admin@192.168.2.236:37779/cam/realmonitor?channel=1&subtype=0"); 46 | map.put("output", "rtmp://192.168.30.21/live/"); 47 | map.put("codec","h264"); 48 | map.put("fmt", "flv"); 49 | map.put("fps", "25"); 50 | map.put("rs", "640x360"); 51 | map.put("twoPart","2"); 52 | //执行任务,id就是appName,如果执行失败返回为null 53 | String id=manager.start(map); 54 | System.out.println(id); 55 | //通过id查询 56 | TaskEntity info=manager.query(id); 57 | System.out.println(info); 58 | //查询全部 59 | Collection infoList=manager.queryAll(); 60 | System.out.println(infoList); 61 | 62 | //停止id对应的任务 63 | manager.stop(id); 64 | 65 | //流式命令行组装执行 66 | manager.start("test1", CommandBuidlerFactory.createBuidler() 67 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 68 | .add("-rtsp_transport","tcp") 69 | .add("-vcodec","copy") 70 | .add("-acodec","copy") 71 | .add("-f","flv") 72 | .add("-y").add("rtmp://eguid.cc/rtmp/test1")); 73 | manager.stop("test1");//停止 74 | 75 | //执行原生ffmpeg命令(不包含ffmpeg的执行路径,该路径会从配置文件中自动读取) 76 | manager.start("test1", "ffmpeg -i input_file -vcodec copy -an output_file_video"); 77 | //包含完整ffmpeg执行路径的命令 78 | manager.start("test2,","d:/ffmpeg/ffmpeg -i input_file -vcodec copy -an output_file_video",true); 79 | //停止全部任务 80 | manager.stopAll(); 81 | 82 | //用于销毁保活线程等 83 | manager.destory(); 84 | ``` 85 | 关于FFmpegCommandHandler接口调用/使用方式也可以参考readme文件 86 | 87 | ## 下个版本构想 88 | 1、新增控制台,web控制台和客户端控制台,可以使用web来管理任务信息查看、发布任务、停止任务等 89 | 2、新增事件回调、命令的执行、停止、中断、保活等都将会使用外部接口回调通知或确认操作 90 | 目前事件回调已经完成,等待下个版本整合进主程序,保活处理器已经完成(已完成,下个版本中提供) 91 | 3、提供web方式的api接口,方便远程调用api来控制 92 | 4、不需要配置文件进行初始化(已完成,下个版本中提供) 93 | 94 | 95 | -------------------------------------------------------------------------------- /loadFFmpeg.properties: -------------------------------------------------------------------------------- 1 | #ffmpeg执行路径,一般为ffmpeg的安装目录,该路径只能是目录,不能为具体文件路径,否则会报错 2 | path=E:/test/ffmpeg/bin/ 3 | #存放任务的默认Map的初始化大小 4 | size=10 5 | #事件回调通知接口地址 6 | callback=http://127.0.0.1/callback 7 | #网络超时设置(毫秒) 8 | timeout=300 9 | 10 | #开启保活线程 11 | keepalive=true 12 | 13 | #是否输出debug消息 14 | debug=true 15 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | cc.eguid.ffch4j 4 | ffch4j 5 | 18.12.02-SNAPSHOT 6 | 7 | src 8 | 9 | 10 | src 11 | 12 | **/*.java 13 | 14 | 15 | 16 | 17 | 18 | maven-compiler-plugin 19 | 3.7.0 20 | 21 | 1.7 22 | 1.7 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/CommandManager.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager; 2 | 3 | import static cc.eguid.commandManager.util.PropertiesUtil.load; 4 | 5 | import java.util.Collection; 6 | import java.util.Map; 7 | 8 | import cc.eguid.commandManager.commandbuidler.CommandAssembly; 9 | import cc.eguid.commandManager.commandbuidler.CommandBuidler; 10 | import cc.eguid.commandManager.config.ProgramConfig; 11 | import cc.eguid.commandManager.data.CommandTasker; 12 | import cc.eguid.commandManager.data.TaskDao; 13 | import cc.eguid.commandManager.handler.TaskHandler; 14 | 15 | /** 16 | * FFmpeg命令操作管理器,可执行FFmpeg命令/停止/查询任务信息 17 | * 18 | * @author eguid 19 | * @since jdk1.7 20 | * @version 2016年10月29日 21 | */ 22 | public interface CommandManager { 23 | 24 | public static final ProgramConfig config=load("loadFFmpeg.properties", ProgramConfig.class); 25 | /** 26 | * 注入自己实现的持久层 27 | * 28 | * @param taskDao 29 | */ 30 | public void setTaskDao(TaskDao taskDao); 31 | 32 | /** 33 | * 注入ffmpeg命令处理器 34 | * 35 | * @param taskHandler 36 | */ 37 | public void setTaskHandler(TaskHandler taskHandler); 38 | 39 | /** 40 | * 注入ffmpeg命令组装器 41 | * 42 | * @param commandAssembly 43 | */ 44 | public void setCommandAssembly(CommandAssembly commandAssembly); 45 | 46 | /** 47 | * 通过命令发布任务(默认命令前不加FFmpeg路径) 48 | * 49 | * @param id - 任务标识 50 | * @param command - FFmpeg命令 51 | * @return 52 | */ 53 | public String start(String id, String command); 54 | /** 55 | * 通过命令发布任务 56 | * @param id - 任务标识 57 | * @param commond - FFmpeg命令 58 | * @param hasPath - 命令中是否包含FFmpeg执行文件的绝对路径 59 | * @return 60 | */ 61 | public String start(String id,String commond,boolean hasPath); 62 | 63 | /** 64 | * 通过流式命令构建器发布任务 65 | * @param commandBuidler 66 | * @return 67 | */ 68 | public String start(String id,CommandBuidler commandBuidler); 69 | 70 | /** 71 | * 通过组装命令发布任务 72 | * 73 | * @param assembly 74 | * -组装命令(详细请参照readme文档说明) 75 | * @return 76 | */ 77 | public String start(Map assembly); 78 | 79 | /** 80 | * 停止任务 81 | * 82 | * @param id 83 | * @return 84 | */ 85 | public boolean stop(String id); 86 | 87 | /** 88 | * 停止全部任务 89 | * 90 | * @return 91 | */ 92 | public int stopAll(); 93 | 94 | /** 95 | * 通过id查询任务信息 96 | * 97 | * @param id 98 | */ 99 | public CommandTasker query(String id); 100 | 101 | /** 102 | * 查询全部任务信息 103 | * 104 | */ 105 | public Collection queryAll(); 106 | 107 | /** 108 | * 销毁一些后台资源和保活线程 109 | */ 110 | public void destory(); 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/CommandManagerImpl.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager; 2 | 3 | import java.util.Collection; 4 | import java.util.Iterator; 5 | import java.util.Map; 6 | 7 | import cc.eguid.commandManager.commandbuidler.CommandAssembly; 8 | import cc.eguid.commandManager.commandbuidler.CommandAssemblyImpl; 9 | import cc.eguid.commandManager.commandbuidler.CommandBuidler; 10 | import cc.eguid.commandManager.data.CommandTasker; 11 | import cc.eguid.commandManager.data.TaskDao; 12 | import cc.eguid.commandManager.data.TaskDaoImpl; 13 | import cc.eguid.commandManager.handler.DefaultOutHandlerMethod; 14 | import cc.eguid.commandManager.handler.KeepAliveHandler; 15 | import cc.eguid.commandManager.handler.OutHandlerMethod; 16 | import cc.eguid.commandManager.handler.TaskHandler; 17 | import cc.eguid.commandManager.handler.TaskHandlerImpl; 18 | 19 | /** 20 | * FFmpeg命令操作管理器 21 | * 22 | * @author eguid 23 | * @since jdk1.7 24 | * @version 2017年10月13日 25 | */ 26 | public class CommandManagerImpl implements CommandManager { 27 | /** 28 | * 任务持久化器 29 | */ 30 | private TaskDao taskDao = null; 31 | /** 32 | * 任务执行处理器 33 | */ 34 | private TaskHandler taskHandler = null; 35 | /** 36 | * 命令组装器 37 | */ 38 | private CommandAssembly commandAssembly = null; 39 | /** 40 | * 任务消息处理器 41 | */ 42 | private OutHandlerMethod ohm = null; 43 | 44 | /** 45 | * 保活处理器 46 | */ 47 | private KeepAliveHandler keepAliveHandler=null; 48 | 49 | /** 50 | * 全部默认初始化,自动查找配置文件 51 | */ 52 | public CommandManagerImpl() { 53 | this(null); 54 | } 55 | 56 | /** 57 | * 指定任务池大小的初始化,其他使用默认 58 | * @param size 59 | */ 60 | public CommandManagerImpl(Integer size) { 61 | init(size); 62 | } 63 | 64 | /** 65 | * 初始化 66 | * @param taskDao 67 | * @param taskHandler 68 | * @param commandAssembly 69 | * @param ohm 70 | * @param size 71 | */ 72 | public CommandManagerImpl(TaskDao taskDao, TaskHandler taskHandler, CommandAssembly commandAssembly, OutHandlerMethod ohm,Integer size) { 73 | super(); 74 | this.taskDao = taskDao; 75 | this.taskHandler = taskHandler; 76 | this.commandAssembly = commandAssembly; 77 | this.ohm = ohm; 78 | init(size); 79 | } 80 | 81 | /** 82 | * 初始化,如果几个处理器未注入,则使用默认处理器 83 | * 84 | * @param size 85 | */ 86 | public void init(Integer size) { 87 | if (config == null) { 88 | System.err.println("配置文件加载失败!配置文件不存在或配置错误"); 89 | return; 90 | } 91 | boolean iskeepalive=false; 92 | if (size == null) { 93 | size = config.getSize() == null ? 10 : config.getSize(); 94 | iskeepalive=config.isKeepalive(); 95 | } 96 | 97 | if (this.ohm == null) { 98 | this.ohm = new DefaultOutHandlerMethod(); 99 | } 100 | 101 | if (this.taskDao == null) { 102 | this.taskDao = new TaskDaoImpl(size); 103 | //初始化保活线程 104 | if(iskeepalive) { 105 | keepAliveHandler = new KeepAliveHandler(taskDao); 106 | keepAliveHandler.start(); 107 | } 108 | } 109 | 110 | if (this.taskHandler == null) { 111 | this.taskHandler = new TaskHandlerImpl(this.ohm); 112 | } 113 | 114 | if (this.commandAssembly == null) { 115 | this.commandAssembly = new CommandAssemblyImpl(); 116 | } 117 | 118 | } 119 | 120 | public void setTaskDao(TaskDao taskDao) { 121 | this.taskDao = taskDao; 122 | } 123 | 124 | public void setTaskHandler(TaskHandler taskHandler) { 125 | this.taskHandler = taskHandler; 126 | } 127 | 128 | public void setCommandAssembly(CommandAssembly commandAssembly) { 129 | this.commandAssembly = commandAssembly; 130 | } 131 | 132 | public void setOhm(OutHandlerMethod ohm) { 133 | this.ohm = ohm; 134 | } 135 | 136 | /** 137 | * 是否已经初始化 138 | * 139 | * @param 如果未初始化时是否初始化 140 | * @return 141 | */ 142 | public boolean isInit(boolean b) { 143 | boolean ret = this.ohm == null || this.taskDao == null || this.taskHandler == null|| this.commandAssembly == null; 144 | if (ret && b) { 145 | init(null); 146 | } 147 | return ret; 148 | } 149 | 150 | @Override 151 | public String start(String id, String command) { 152 | return start(id, command, false); 153 | } 154 | 155 | @Override 156 | public String start(String id, String command, boolean hasPath) { 157 | if (isInit(true)) { 158 | System.err.println("执行失败,未进行初始化或初始化失败!"); 159 | return null; 160 | } 161 | if (id != null && command != null) { 162 | CommandTasker tasker = taskHandler.process(id, hasPath ? command : config.getPath() + command); 163 | if (tasker != null) { 164 | int ret = taskDao.add(tasker); 165 | if (ret > 0) { 166 | return tasker.getId(); 167 | } else { 168 | // 持久化信息失败,停止处理 169 | taskHandler.stop(tasker.getProcess(), tasker.getThread()); 170 | if (config.isDebug()) 171 | System.err.println("持久化失败,停止任务!"); 172 | } 173 | } 174 | } 175 | return null; 176 | } 177 | 178 | @Override 179 | public String start(Map assembly) { 180 | // ffmpeg环境是否配置正确 181 | if (checkConfig()) { 182 | System.err.println("配置未正确加载,无法执行"); 183 | return null; 184 | } 185 | // 参数是否符合要求 186 | if (assembly == null || assembly.isEmpty() || !assembly.containsKey("appName")) { 187 | System.err.println("参数不正确,无法执行"); 188 | return null; 189 | } 190 | String appName = (String) assembly.get("appName"); 191 | if (appName != null && "".equals(appName.trim())) { 192 | System.err.println("appName不能为空"); 193 | return null; 194 | } 195 | assembly.put("ffmpegPath", config.getPath() + "ffmpeg"); 196 | String command = commandAssembly.assembly(assembly); 197 | if (command != null) { 198 | return start(appName, command, true); 199 | } 200 | 201 | return null; 202 | } 203 | 204 | @Override 205 | public String start(String id,CommandBuidler commandBuidler) { 206 | // ffmpeg环境是否配置正确 207 | if (checkConfig()) { 208 | System.err.println("配置未正确加载,无法执行"); 209 | return null; 210 | } 211 | String command =commandBuidler.get(); 212 | if (command != null) { 213 | return start(id, command, true); 214 | } 215 | return null; 216 | } 217 | 218 | private boolean checkConfig() { 219 | return config == null; 220 | } 221 | 222 | @Override 223 | public boolean stop(String id) { 224 | if (id != null && taskDao.isHave(id)) { 225 | if (config.isDebug()) 226 | System.out.println("正在停止任务:" + id); 227 | CommandTasker tasker = taskDao.get(id); 228 | if (taskHandler.stop(tasker.getProcess(), tasker.getThread())) { 229 | taskDao.remove(id); 230 | return true; 231 | } 232 | } 233 | System.err.println("停止任务失败!id=" + id); 234 | return false; 235 | } 236 | 237 | @Override 238 | public int stopAll() { 239 | Collection list = taskDao.getAll(); 240 | Iterator iter = list.iterator(); 241 | CommandTasker tasker = null; 242 | int index = 0; 243 | while (iter.hasNext()) { 244 | tasker = iter.next(); 245 | if (taskHandler.stop(tasker.getProcess(), tasker.getThread())) { 246 | taskDao.remove(tasker.getId()); 247 | index++; 248 | } 249 | } 250 | if (config.isDebug()) 251 | System.out.println("停止了" + index + "个任务!"); 252 | return index; 253 | } 254 | 255 | @Override 256 | public CommandTasker query(String id) { 257 | return taskDao.get(id); 258 | } 259 | 260 | @Override 261 | public Collection queryAll() { 262 | return taskDao.getAll(); 263 | } 264 | 265 | @Override 266 | public void destory() { 267 | if(keepAliveHandler!=null) { 268 | //安全停止保活线程 269 | keepAliveHandler.interrupt(); 270 | } 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/callback/EventCallBack.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.callback; 2 | 3 | import cc.eguid.commandManager.data.CommandTasker; 4 | 5 | /** 6 | * 事件回调 7 | * @author eguid 8 | * 9 | */ 10 | public interface EventCallBack { 11 | 12 | /** 13 | * 命令行执行开始事件 14 | * @param t -事件类型 15 | * @param tasker -任务信息 16 | */ 17 | boolean callback(EventCallBackType t,CommandTasker tasker); 18 | } 19 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/callback/EventCallBackType.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.callback; 2 | 3 | /** 4 | * 事件回调类型 5 | * @author eguid 6 | * 7 | */ 8 | public enum EventCallBackType { 9 | exec,//执行命令后通知 10 | stop,//停止命令后通知 11 | interrupt,//进程中断后通知 12 | heartbeat,//主进程存活心跳 13 | } 14 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/callback/worker/EventMsgNetWorker.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.callback.worker; 2 | 3 | import java.io.IOException; 4 | import java.net.URL; 5 | import java.net.URLConnection; 6 | import java.util.Queue; 7 | import java.util.concurrent.ConcurrentLinkedQueue; 8 | 9 | import cc.eguid.commandManager.CommandManager; 10 | import cc.eguid.commandManager.callback.EventCallBack; 11 | import cc.eguid.commandManager.callback.EventCallBackType; 12 | import cc.eguid.commandManager.data.CommandTasker; 13 | import cc.eguid.commandManager.data.TaskerEventMsg; 14 | 15 | /** 16 | * 事件消息独立发送线程 17 | * 18 | * @author eguid 19 | * 20 | */ 21 | public class EventMsgNetWorker extends Thread implements EventCallBack{ 22 | 23 | protected static Queue queue = null;// 一个事件消息队列,发送失败的事件消息将会进入队列队尾等待下次再次发送 24 | 25 | // 一个网络库,用于快速发送http消息 26 | private int timeout = 300;// 默认300毫秒 27 | 28 | public EventMsgNetWorker(int timeout) { 29 | super(); 30 | this.timeout = timeout; 31 | queue = new ConcurrentLinkedQueue<>(); 32 | } 33 | 34 | @Override 35 | public void run() { 36 | for (;;) { 37 | try { 38 | while (queue.peek() != null) { 39 | TaskerEventMsg t = queue.poll(); 40 | // 借助网络库发送该消息 41 | String url = CommandManager.config.getCallback(); 42 | if (reqGET(url)) { 43 | System.err.println("发送成功"); 44 | } else { 45 | System.err.println("发送失败"); 46 | // 发送失败的事件消息将会进入队列队尾等待下次再次发送 47 | queue.offer(t); 48 | } 49 | } 50 | } catch (Exception e) { 51 | 52 | } 53 | } 54 | 55 | } 56 | 57 | /** 58 | * 发送get请求 59 | */ 60 | private boolean reqGET(String url) { 61 | URL realUrl; 62 | // PrintWriter out = null; 63 | try { 64 | realUrl = new URL(url); 65 | // 打开和URL之间的连接 66 | URLConnection connection = realUrl.openConnection(); 67 | // 设置通用的请求属性 68 | connection.setUseCaches(false); 69 | connection.setConnectTimeout(timeout); 70 | connection.setRequestProperty("accept", "*/*"); 71 | connection.setRequestProperty("connection", "Keep-Alive"); 72 | connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 73 | connection.setDoOutput(false); 74 | connection.setDoInput(false); 75 | connection.connect(); 76 | return true; 77 | } catch (IOException e) { 78 | return false; 79 | } 80 | } 81 | 82 | @Override 83 | public boolean callback(EventCallBackType ecbt, CommandTasker tasker) { 84 | return queue.add(new TaskerEventMsg(ecbt, tasker)); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/commandbuidler/CommandAssembly.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.commandbuidler; 2 | 3 | import java.util.Map; 4 | /** 5 | * 命令组装器接口 6 | * @author eguid 7 | * @since jdk1.7 8 | * @version 2016年10月29日 9 | */ 10 | public interface CommandAssembly { 11 | /** 12 | * 将参数转为ffmpeg命令 13 | * @param paramMap 14 | * @return 15 | */ 16 | public String assembly(Map paramMap); 17 | 18 | public String assembly(); 19 | } 20 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/commandbuidler/CommandAssemblyImpl.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.commandbuidler; 2 | 3 | import java.util.Map; 4 | /** 5 | * 默认命令组装器实现 6 | * @author eguid 7 | * @since jdk1.7 8 | * @version 2016年10月29日 9 | */ 10 | public class CommandAssemblyImpl implements CommandAssembly{ 11 | /** 12 | * 13 | * @param map 14 | * -要组装的map 15 | * @param id 16 | * -返回参数:id 17 | * @param id 18 | * -返回参数:组装好的命令 19 | * @return 20 | */ 21 | public String assembly(Map paramMap) { 22 | try { 23 | if (paramMap.containsKey("ffmpegPath")) { 24 | String ffmpegPath = (String) paramMap.get("ffmpegPath"); 25 | // -i:输入流地址或者文件绝对地址 26 | StringBuilder comm = new StringBuilder(ffmpegPath + " -i "); 27 | // 是否有必输项:输入地址,输出地址,应用名,twoPart:0-推一个元码流;1-推一个自定义推流;2-推两个流(一个是自定义,一个是元码) 28 | if (paramMap.containsKey("input") && paramMap.containsKey("output") && paramMap.containsKey("appName") 29 | && paramMap.containsKey("twoPart")) { 30 | String input = (String) paramMap.get("input"); 31 | String output = (String) paramMap.get("output"); 32 | String appName = (String) paramMap.get("appName"); 33 | String twoPart = (String) paramMap.get("twoPart"); 34 | String codec = (String) paramMap.get("codec"); 35 | // 默认h264解码 36 | codec = (codec == null ? "h264" : (String) paramMap.get("codec")); 37 | // 输入地址 38 | comm.append(input); 39 | // 当twoPart为0时,只推一个元码流 40 | if ("0".equals(twoPart)) { 41 | comm.append(" -vcodec " + codec + " -f flv -an " + output + appName); 42 | } else { 43 | // -f :转换格式,默认flv 44 | if (paramMap.containsKey("fmt")) { 45 | String fmt = (String) paramMap.get("fmt"); 46 | comm.append(" -f " + fmt); 47 | } 48 | // -r :帧率,默认25;-g :帧间隔 49 | if (paramMap.containsKey("fps")) { 50 | String fps = (String) paramMap.get("fps"); 51 | comm.append(" -r " + fps); 52 | comm.append(" -g " + fps); 53 | } 54 | // -s 分辨率 默认是原分辨率 55 | if (paramMap.containsKey("rs")) { 56 | String rs = (String) paramMap.get("rs"); 57 | comm.append(" -s " + rs); 58 | } 59 | // 输出地址+发布的应用名 60 | comm.append(" -an " + output + appName); 61 | // 当twoPart为2时推两个流,一个自定义流,一个元码流 62 | if ("2".equals(twoPart)) { 63 | // 一个视频源,可以有多个输出,第二个输出为拷贝源视频输出,不改变视频的各项参数并且命名为应用名+HD 64 | comm.append(" -vcodec copy -f flv -an ").append(output + appName + "HD"); 65 | } 66 | } 67 | return comm.toString(); 68 | } 69 | } 70 | } catch (Exception e) { 71 | return null; 72 | } 73 | return null; 74 | } 75 | 76 | @Override 77 | public String assembly() { 78 | // TODO Auto-generated method stub 79 | return null; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/commandbuidler/CommandBuidler.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.commandbuidler; 2 | 3 | /** 4 | * 流式命令行构建器 5 | * 6 | * @author eguid 7 | */ 8 | public interface CommandBuidler { 9 | 10 | /** 11 | * 创建命令行 12 | * 13 | * @param root 14 | * -命令行运行根目录或FFmpeg可执行文件安装目录 15 | * @return 16 | */ 17 | CommandBuidler create(String root); 18 | 19 | /** 20 | * 创建默认根目录或默认FFmpeg可执行文件安装目录 21 | * 22 | * @return 23 | */ 24 | CommandBuidler create(); 25 | 26 | /** 27 | * 累加键-值命令 28 | * 29 | * @param key 30 | * @param val 31 | * @return 32 | */ 33 | CommandBuidler add(String key, String val); 34 | 35 | /** 36 | * 累加命令 37 | * 38 | * @param val 39 | * @return 40 | */ 41 | CommandBuidler add(String val); 42 | 43 | /** 44 | * 生成完整命令行 45 | * 46 | * @return 47 | */ 48 | CommandBuidler build(); 49 | 50 | /** 51 | * 获取已经构建好的命令行 52 | * @return 53 | */ 54 | String get(); 55 | } 56 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/commandbuidler/CommandBuidlerFactory.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.commandbuidler; 2 | 3 | /** 4 | * 默认流式命令构建器工厂类 5 | * @author eguid 6 | * 7 | */ 8 | public class CommandBuidlerFactory { 9 | 10 | public static CommandBuidler createBuidler() { 11 | return new DefaultCommandBuidler(); 12 | }; 13 | 14 | public static CommandBuidler createBuidler(String rootpath) { 15 | return new DefaultCommandBuidler(rootpath); 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/commandbuidler/DefaultCommandBuidler.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.commandbuidler; 2 | 3 | import cc.eguid.commandManager.CommandManager; 4 | 5 | /** 6 | * 默认流式命令行构建器(非线程安全) 7 | * @author eguid 8 | */ 9 | public class DefaultCommandBuidler implements CommandBuidler{ 10 | 11 | StringBuilder buidler=null; 12 | String command=null; 13 | 14 | public DefaultCommandBuidler() { 15 | create(); 16 | } 17 | 18 | 19 | public DefaultCommandBuidler(String rootpath) { 20 | create(rootpath); 21 | } 22 | 23 | 24 | @Override 25 | public CommandBuidler create(String rootpath) { 26 | buidler=new StringBuilder(rootpath); 27 | return this; 28 | } 29 | 30 | @Override 31 | public CommandBuidler create() { 32 | return create(CommandManager.config.getPath()); 33 | } 34 | 35 | @Override 36 | public CommandBuidler add(String key, String val) { 37 | return add(key).add(val); 38 | } 39 | 40 | @Override 41 | public CommandBuidler add(String val) { 42 | if(buidler!=null) { 43 | buidler.append(val); 44 | addBlankspace(); 45 | } 46 | return this; 47 | } 48 | 49 | @Override 50 | public CommandBuidler build() { 51 | if(buidler!=null) { 52 | command=buidler.toString(); 53 | } 54 | return this; 55 | } 56 | 57 | private void addBlankspace() { 58 | buidler.append(" "); 59 | } 60 | 61 | @Override 62 | public String get() { 63 | if(command==null) { 64 | build(); 65 | } 66 | return command; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/config/ProgramConfig.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.config; 2 | 3 | /** 4 | * 程序基础配置 5 | * 6 | * @author eguid 7 | * 8 | */ 9 | public class ProgramConfig { 10 | 11 | private String path;//默认命令行执行根路径 12 | private boolean debug;//是否开启debug模式 13 | private Integer size;//任务池大小 14 | private String callback;//回调通知地址 15 | private boolean keepalive;//是否开启保活 16 | 17 | public String getPath() { 18 | return path; 19 | } 20 | 21 | public void setPath(String path) { 22 | this.path = path; 23 | } 24 | 25 | public boolean isDebug() { 26 | return debug; 27 | } 28 | 29 | public void setDebug(boolean debug) { 30 | this.debug = debug; 31 | } 32 | 33 | public Integer getSize() { 34 | return size; 35 | } 36 | 37 | public void setSize(Integer size) { 38 | this.size = size; 39 | } 40 | 41 | public String getCallback() { 42 | return callback; 43 | } 44 | 45 | public void setCallback(String callback) { 46 | this.callback = callback; 47 | } 48 | 49 | public boolean isKeepalive() { 50 | return keepalive; 51 | } 52 | 53 | public void setKeepalive(boolean keepalive) { 54 | this.keepalive = keepalive; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return "ProgramConfig [path=" + path + ", debug=" + debug + ", size=" + size + ", callback=" + callback 60 | + ", keepalive=" + keepalive + "]"; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/config/defaultFFmpegConfig.properties: -------------------------------------------------------------------------------- 1 | #ffmpeg执行路径,一般为ffmpeg的安装目录,该路径只能是目录,不能为具体文件路径,否则会报错 2 | path=E:/test/ffmpeg/bin/ 3 | #是否启用默认的ffmpeg,如果启用默认ffmpeg,上面配置的path就没有用了 4 | defaultpathEnable=true 5 | #存放任务的默认Map的初始化大小 6 | size=10 7 | #事件回调通知接口地址 8 | callback=http://127.0.0.1/callback 9 | #网络超时设置(毫秒) 10 | timeout=300 11 | #开启保活线程 12 | keepalive=true 13 | #是否输出debug消息 14 | debug=true 15 | 16 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/data/CommandTasker.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.data; 2 | 3 | import cc.eguid.commandManager.handler.OutHandler; 4 | 5 | /** 6 | * 用于存放任务id,任务主进程,任务输出线程 7 | * 8 | * @author eguid 9 | * @since jdk1.7 10 | * @version 2016年10月29日 11 | */ 12 | public class CommandTasker { 13 | private final String id;// 任务id 14 | private final String command;//命令行 15 | private Process process;// 命令行运行主进程 16 | private OutHandler thread;// 命令行消息输出子线程 17 | 18 | public CommandTasker(String id,String command) { 19 | this.id = id; 20 | this.command=command; 21 | } 22 | 23 | public CommandTasker(String id,String command, Process process, OutHandler thread) { 24 | this.id = id; 25 | this.command=command; 26 | this.process = process; 27 | this.thread = thread; 28 | } 29 | 30 | public String getId() { 31 | return id; 32 | } 33 | 34 | public Process getProcess() { 35 | return process; 36 | } 37 | 38 | public OutHandler getThread() { 39 | return thread; 40 | } 41 | 42 | public String getCommand() { 43 | return command; 44 | } 45 | 46 | public void setProcess(Process process) { 47 | this.process = process; 48 | } 49 | 50 | public void setThread(OutHandler thread) { 51 | this.thread = thread; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return "CommandTasker [id=" + id + ", command=" + command + ", process=" + process + ", thread=" + thread + "]"; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/data/TaskDao.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.data; 2 | 3 | import java.util.Collection; 4 | 5 | /** 6 | * 任务信息持久层接口 7 | * @author eguid 8 | * @since jdk1.7 9 | * @version 2016年10月29日 10 | */ 11 | public interface TaskDao { 12 | /** 13 | * 通过id查询任务信息 14 | * @param id - 任务ID 15 | * @return CommandTasker -任务实体 16 | */ 17 | public CommandTasker get(String id); 18 | /** 19 | * 查询全部任务信息 20 | * @return Collection 21 | */ 22 | public Collection getAll(); 23 | /** 24 | * 增加任务信息 25 | * @param CommandTasker -任务信息实体 26 | * @return 增加数量:<1-增加失败,>=1-增加成功 27 | */ 28 | public int add(CommandTasker CommandTasker); 29 | /** 30 | * 删除id对应的任务信息 31 | * @param id 32 | * @return 数量:<1-操作失败,>=1-操作成功 33 | */ 34 | public int remove(String id); 35 | /** 36 | * 删除全部任务信息 37 | * @return 数量:<1-操作失败,>=1-操作成功 38 | */ 39 | public int removeAll(); 40 | /** 41 | * 是否存在某个ID 42 | * @param id - 任务ID 43 | * @return true:存在,false:不存在 44 | */ 45 | public boolean isHave(String id); 46 | } 47 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/data/TaskDaoImpl.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.data; 2 | 3 | import java.util.Collection; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | import java.util.concurrent.ConcurrentMap; 6 | 7 | /** 8 | * 任务信息持久层实现 9 | * 10 | * @author eguid 11 | * @since jdk1.7 12 | * @version 2016年10月29日 13 | */ 14 | public class TaskDaoImpl implements TaskDao { 15 | // 存放任务信息 16 | private ConcurrentMap map = null; 17 | 18 | public TaskDaoImpl(int size) { 19 | map = new ConcurrentHashMap<>(size); 20 | } 21 | 22 | @Override 23 | public CommandTasker get(String id) { 24 | return map.get(id); 25 | } 26 | 27 | @Override 28 | public Collection getAll() { 29 | return map.values(); 30 | } 31 | 32 | @Override 33 | public int add(CommandTasker CommandTasker) { 34 | String id = CommandTasker.getId(); 35 | if (id != null && !map.containsKey(id)) { 36 | map.put(CommandTasker.getId(), CommandTasker); 37 | if(map.get(id)!=null) 38 | { 39 | return 1; 40 | } 41 | } 42 | return 0; 43 | } 44 | 45 | @Override 46 | public int remove(String id) { 47 | if(map.remove(id) != null){ 48 | return 1; 49 | }; 50 | return 0; 51 | } 52 | 53 | @Override 54 | public int removeAll() { 55 | int size = map.size(); 56 | try { 57 | map.clear(); 58 | } catch (Exception e) { 59 | return 0; 60 | } 61 | return size; 62 | } 63 | 64 | @Override 65 | public boolean isHave(String id) { 66 | return map.containsKey(id); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/data/TaskerEventMsg.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.data; 2 | 3 | import cc.eguid.commandManager.callback.EventCallBackType; 4 | 5 | /** 6 | * 命令行事件消息 7 | * @author eguid 8 | * 9 | */ 10 | public class TaskerEventMsg { 11 | EventCallBackType ecbt; 12 | CommandTasker tasker; 13 | 14 | public TaskerEventMsg(EventCallBackType ecbt, CommandTasker tasker) { 15 | super(); 16 | this.ecbt = ecbt; 17 | this.tasker = tasker; 18 | } 19 | 20 | public EventCallBackType getEcbt() { 21 | return ecbt; 22 | } 23 | 24 | public void setEcbt(EventCallBackType ecbt) { 25 | this.ecbt = ecbt; 26 | } 27 | 28 | public CommandTasker getTasker() { 29 | return tasker; 30 | } 31 | 32 | public void setTasker(CommandTasker tasker) { 33 | this.tasker = tasker; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return "CommandEventMsg [ecbt=" + ecbt + ", tasker=" + tasker + "]"; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/handler/DefaultOutHandlerMethod.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.handler; 2 | /** 3 | * 默认任务消息输出处理 4 | * @author eguid 5 | * @since jdk1.7 6 | * @version 2017年10月13日 7 | */ 8 | public class DefaultOutHandlerMethod implements OutHandlerMethod{ 9 | 10 | /** 11 | * 任务是否异常中断,如果 12 | */ 13 | public boolean isBroken=false; 14 | 15 | @Override 16 | public void parse(String id,String msg) { 17 | //过滤消息 18 | if (msg.indexOf("fail") != -1) { 19 | System.err.println(id + "任务可能发生故障:" + msg); 20 | System.err.println("失败,设置中断状态"); 21 | isBroken=true; 22 | }else if(msg.indexOf("miss")!= -1) { 23 | System.err.println(id + "任务可能发生丢包:" + msg); 24 | System.err.println("失败,设置中断状态"); 25 | isBroken=true; 26 | }else { 27 | isBroken=false; 28 | System.err.println(id + "消息:" + msg); 29 | 30 | } 31 | 32 | } 33 | 34 | @Override 35 | public boolean isbroken() { 36 | return isBroken; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/handler/KeepAliveHandler.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.handler; 2 | 3 | import java.io.IOException; 4 | import java.util.Queue; 5 | import java.util.concurrent.ConcurrentLinkedQueue; 6 | 7 | import cc.eguid.commandManager.data.CommandTasker; 8 | import cc.eguid.commandManager.data.TaskDao; 9 | import cc.eguid.commandManager.util.ExecUtil; 10 | 11 | /** 12 | * 任务保活处理器(一个后台保活线程,用于处理异常中断的持久任务) 13 | * @author eguid 14 | * 15 | */ 16 | public class KeepAliveHandler extends Thread{ 17 | /**待处理队列*/ 18 | private static Queue queue=null; 19 | 20 | public int err_index=0;//错误计数 21 | 22 | public volatile int stop_index=0;//安全停止线程标记 23 | 24 | /** 任务持久化器*/ 25 | private TaskDao taskDao = null; 26 | 27 | public KeepAliveHandler(TaskDao taskDao) { 28 | super(); 29 | this.taskDao=taskDao; 30 | queue=new ConcurrentLinkedQueue<>(); 31 | } 32 | 33 | public static void add(String id ) { 34 | if(queue!=null) { 35 | queue.offer(id); 36 | } 37 | } 38 | 39 | public boolean stop(Process process) { 40 | if (process != null) { 41 | process.destroy(); 42 | return true; 43 | } 44 | return false; 45 | } 46 | 47 | @Override 48 | public void run() { 49 | for(;stop_index==0;) { 50 | if(queue==null) { 51 | continue; 52 | } 53 | String id=null; 54 | CommandTasker task=null; 55 | 56 | try { 57 | while(queue.peek() != null) { 58 | System.err.println("准备重启任务:"+queue); 59 | id=queue.poll(); 60 | task=taskDao.get(id); 61 | //重启任务 62 | ExecUtil.restart(task); 63 | } 64 | }catch(IOException e) { 65 | System.err.println(id+" 任务重启失败,详情:"+task); 66 | //重启任务失败 67 | err_index++; 68 | }catch(Exception e) { 69 | 70 | } 71 | } 72 | } 73 | 74 | @Override 75 | public void interrupt() { 76 | stop_index=1; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/handler/OutHandler.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.handler; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | 8 | import cc.eguid.commandManager.CommandManager; 9 | 10 | /** 11 | * 任务消息输出处理器 12 | * @author eguid 13 | * @since jdk1.7 14 | * @version 2017年10月13日 15 | */ 16 | public class OutHandler extends Thread { 17 | /**控制状态 */ 18 | private volatile boolean desstatus = true; 19 | 20 | /**读取输出流*/ 21 | private BufferedReader br = null; 22 | 23 | /**任务ID*/ 24 | private String id = null; 25 | 26 | /**消息处理方法*/ 27 | private OutHandlerMethod ohm; 28 | 29 | /** 30 | * 创建输出线程(默认立即开启线程) 31 | * @param is 32 | * @param id 33 | * @param ohm 34 | * @return 35 | */ 36 | public static OutHandler create(InputStream is, String id,OutHandlerMethod ohm) { 37 | return create(is, id, ohm,true); 38 | } 39 | 40 | /** 41 | * 创建输出线程 42 | * @param is 43 | * @param id 44 | * @param ohm 45 | * @param start-是否立即开启线程 46 | * @return 47 | */ 48 | public static OutHandler create(InputStream is, String id,OutHandlerMethod ohm,boolean start) { 49 | OutHandler out= new OutHandler(is, id, ohm); 50 | if(start) 51 | out.start(); 52 | return out; 53 | } 54 | 55 | public void setOhm(OutHandlerMethod ohm) { 56 | this.ohm = ohm; 57 | } 58 | 59 | public void setDesStatus(boolean desStatus) { 60 | this.desstatus = desStatus; 61 | } 62 | 63 | public void setId(String id) { 64 | this.id = id; 65 | } 66 | 67 | public OutHandlerMethod getOhm() { 68 | return ohm; 69 | } 70 | 71 | public OutHandler(InputStream is, String id,OutHandlerMethod ohm) { 72 | br = new BufferedReader(new InputStreamReader(is)); 73 | this.id = id; 74 | this.ohm=ohm; 75 | } 76 | 77 | /** 78 | * 重写线程销毁方法,安全的关闭线程 79 | */ 80 | @Override 81 | public void destroy() { 82 | setDesStatus(false); 83 | } 84 | 85 | /** 86 | * 执行输出线程 87 | */ 88 | @Override 89 | public void run() { 90 | String msg = null; 91 | try { 92 | if (CommandManager.config.isDebug()) { 93 | System.out.println(id + "开始推流!"); 94 | } 95 | while (desstatus && (msg = br.readLine()) != null) { 96 | ohm.parse(id,msg); 97 | if(ohm.isbroken()) { 98 | System.err.println("检测到中断,提交重启任务给保活处理器"); 99 | //如果发生异常中断,立即进行保活 100 | //把中断的任务交给保活处理器进行进一步处理 101 | KeepAliveHandler.add(id); 102 | } 103 | } 104 | } catch (IOException e) { 105 | System.out.println("发生内部异常错误,自动关闭[" + this.getId() + "]线程"); 106 | destroy(); 107 | } finally { 108 | if (this.isAlive()) { 109 | destroy(); 110 | } 111 | } 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/handler/OutHandlerMethod.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.handler; 2 | /** 3 | * 输出消息处理 4 | * @author eguid 5 | * @since jdk1.7 6 | * @version 2017年10月13日 7 | */ 8 | public interface OutHandlerMethod { 9 | /** 10 | * 解析消息 11 | * @param id-任务ID 12 | * @param msg -消息 13 | */ 14 | public void parse(String id, String msg); 15 | 16 | /** 17 | * 任务是否异常中断 18 | * @return 19 | */ 20 | public boolean isbroken(); 21 | } 22 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/handler/TaskHandler.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.handler; 2 | 3 | import cc.eguid.commandManager.data.CommandTasker; 4 | /** 5 | * 任务执行接口 6 | * @author eguid 7 | * @since jdk1.7 8 | * @version 2016年10月29日 9 | */ 10 | public interface TaskHandler { 11 | /** 12 | * 按照命令执行主进程和输出线程 13 | * 14 | * @param id 15 | * @param command 16 | * @return 17 | */ 18 | public CommandTasker process(String id, String command); 19 | 20 | /** 21 | * 停止主进程(停止主进程需要保证输出线程已经关闭,否则输出线程会出错) 22 | * 23 | * @param process 24 | * @return 25 | */ 26 | public boolean stop(Process process); 27 | 28 | /** 29 | * 停止输出线程 30 | * 31 | * @param thread 32 | * @return 33 | */ 34 | public boolean stop(Thread thread); 35 | 36 | /** 37 | * 正确的停止输出线程和主进程 38 | * 39 | * @param process 40 | * @param thread 41 | * @return 42 | */ 43 | public boolean stop(Process process, Thread thread); 44 | } 45 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/handler/TaskHandlerImpl.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.handler; 2 | 3 | import java.io.IOException; 4 | 5 | import cc.eguid.commandManager.CommandManager; 6 | import cc.eguid.commandManager.data.CommandTasker; 7 | import cc.eguid.commandManager.util.ExecUtil; 8 | /** 9 | * 任务处理实现 10 | * @author eguid 11 | * @since jdk1.7 12 | * @version 2016年10月29日 13 | */ 14 | public class TaskHandlerImpl implements TaskHandler { 15 | 16 | private OutHandlerMethod ohm=null; 17 | 18 | public TaskHandlerImpl(OutHandlerMethod ohm) { 19 | this.ohm = ohm; 20 | } 21 | 22 | public void setOhm(OutHandlerMethod ohm) { 23 | this.ohm = ohm; 24 | } 25 | 26 | @Override 27 | public CommandTasker process(String id, String command) { 28 | CommandTasker tasker = null; 29 | try { 30 | tasker =ExecUtil.createTasker(id,command,ohm); 31 | 32 | if(CommandManager.config.isDebug()) 33 | System.out.println(id+" 执行命令行:"+command); 34 | 35 | return tasker; 36 | } catch (IOException e) { 37 | //运行失败,停止任务 38 | ExecUtil.stop(tasker); 39 | 40 | if(CommandManager.config.isDebug()) 41 | System.err.println(id+" 执行命令失败!进程和输出线程已停止"); 42 | 43 | // 出现异常说明开启失败,返回null 44 | return null; 45 | } 46 | } 47 | 48 | @Override 49 | public boolean stop(Process process) { 50 | return ExecUtil.stop(process); 51 | } 52 | 53 | @Override 54 | public boolean stop(Thread outHandler) { 55 | return ExecUtil.stop(outHandler); 56 | } 57 | 58 | @Override 59 | public boolean stop(Process process, Thread thread) { 60 | boolean ret=false; 61 | ret=stop(thread); 62 | ret=stop(process); 63 | return ret; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/test/Test.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.test; 2 | 3 | import java.util.Collection; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import cc.eguid.commandManager.CommandManager; 8 | import cc.eguid.commandManager.CommandManagerImpl; 9 | import cc.eguid.commandManager.commandbuidler.CommandBuidlerFactory; 10 | import cc.eguid.commandManager.data.CommandTasker; 11 | /** 12 | * 测试 13 | * @author eguid 14 | * @since jdk1.7 15 | * @version 2017年10月13日 16 | */ 17 | public class Test { 18 | /** 19 | * 命令组装器测试 20 | * @throws InterruptedException 21 | */ 22 | public static void test1() throws InterruptedException{ 23 | CommandManager manager = new CommandManagerImpl(); 24 | Map map = new HashMap(); 25 | map.put("appName", "test123"); 26 | map.put("input", "rtsp://admin:admin@192.168.2.236:37779/cam/realmonitor?channel=1&subtype=0"); 27 | map.put("output", "rtmp://192.168.30.21/live/"); 28 | map.put("codec", "h264"); 29 | map.put("fmt", "flv"); 30 | map.put("fps", "25"); 31 | map.put("rs", "640x360"); 32 | map.put("twoPart", "2"); 33 | // 执行任务,id就是appName,如果执行失败返回为null 34 | String id = manager.start(map); 35 | System.out.println(id); 36 | // 通过id查询 37 | CommandTasker info = manager.query(id); 38 | System.out.println(info); 39 | // 查询全部 40 | Collection infoList = manager.queryAll(); 41 | System.out.println(infoList); 42 | Thread.sleep(30000); 43 | // 停止id对应的任务 44 | manager.stop(id); 45 | } 46 | /** 47 | * 默认方式,rtsp->rtmp转流单个命令测试 48 | * @throws InterruptedException 49 | */ 50 | public static void test2() throws InterruptedException{ 51 | CommandManager manager = new CommandManagerImpl(); 52 | // -rtsp_transport tcp 53 | //测试多个任何同时执行和停止情况 54 | //默认方式发布任务 55 | manager.start("tomcat", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat"); 56 | 57 | Thread.sleep(30000); 58 | // 停止全部任务 59 | manager.stopAll(); 60 | } 61 | /** 62 | * 完整ffmpeg路径测试 63 | * @throws InterruptedException 64 | */ 65 | public static void test4() throws InterruptedException{ 66 | CommandManager manager = new CommandManagerImpl(); 67 | // -rtsp_transport tcp 68 | //测试多个任何同时执行和停止情况 69 | //默认方式发布任务 70 | manager.start("tomcat", "D:/TestWorkspaces/FFmpegCommandHandler/src/cc/eguid/FFmpegCommandManager/ffmpeg/ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat",true); 71 | 72 | Thread.sleep(30000); 73 | // 停止全部任务 74 | manager.stopAll(); 75 | } 76 | 77 | /** 78 | * rtsp-rtmp转流多任务测试 79 | * @throws InterruptedException 80 | */ 81 | public static void test3() throws InterruptedException{ 82 | CommandManager manager = new CommandManagerImpl(); 83 | // -rtsp_transport tcp 84 | //测试多个任何同时执行和停止情况 85 | //false表示使用配置文件中的ffmpeg路径,true表示本条命令已经包含ffmpeg所在的完整路径 86 | manager.start("tomcat", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat",false); 87 | manager.start("tomcat1", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat1",false); 88 | manager.start("tomcat2", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat2",false); 89 | manager.start("tomcat3", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat3",false); 90 | manager.start("tomcat4", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat4",false); 91 | manager.start("tomcat5", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat5",false); 92 | manager.start("tomcat6", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat6",false); 93 | manager.start("tomcat7", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat7",false); 94 | manager.start("tomcat8", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat8",false); 95 | manager.start("tomcat9", "ffmpeg -i rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov -vcodec copy -acodec copy -f flv -y rtmp://106.14.182.20:1935/rtmp/tomcat9",false); 96 | 97 | Thread.sleep(30000); 98 | // 停止全部任务 99 | manager.stopAll(); 100 | } 101 | 102 | /** 103 | * 测试流式命令行构建器 104 | * @throws InterruptedException 105 | */ 106 | public static void testStreamCommandAssmbly() throws InterruptedException { 107 | CommandManager manager = new CommandManagerImpl(); 108 | manager.start("test1", CommandBuidlerFactory.createBuidler() 109 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 110 | .add("-rtsp_transport","tcp") 111 | .add("-vcodec","copy") 112 | .add("-acodec","copy") 113 | .add("-f","flv") 114 | .add("-y").add("rtmp://106.14.182.20:1935/rtmp/test1")); 115 | Thread.sleep(30000); 116 | // 停止全部任务 117 | manager.stopAll(); 118 | } 119 | /** 120 | * 测试任务中断自动重启任务 121 | * @throws InterruptedException 122 | */ 123 | public static void testBroken() throws InterruptedException { 124 | CommandManager manager = new CommandManagerImpl(); 125 | manager.start("test1", CommandBuidlerFactory.createBuidler() 126 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 127 | .add("-rtsp_transport","tcp") 128 | .add("-vcodec","copy") 129 | .add("-acodec","copy") 130 | .add("-f","flv") 131 | .add("-y").add("rtmp://106.14.182.20:1935/rtmp/test1")); 132 | Thread.sleep(30000); 133 | // 停止全部任务 134 | manager.stopAll(); 135 | manager.destory(); 136 | } 137 | /** 138 | * 批量测试任务中断自动重启任务 139 | * @throws InterruptedException 140 | */ 141 | public static void testBrokenMuti() throws InterruptedException { 142 | CommandManager manager = new CommandManagerImpl(); 143 | manager.start("test1", CommandBuidlerFactory.createBuidler() 144 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 145 | .add("-rtsp_transport","tcp") 146 | .add("-vcodec","copy") 147 | .add("-acodec","copy") 148 | .add("-f","flv") 149 | .add("-y").add("rtmp://106.14.182.20:1935/rtmp/test1")); 150 | manager.start("test2", CommandBuidlerFactory.createBuidler() 151 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 152 | .add("-rtsp_transport","tcp") 153 | .add("-vcodec","copy") 154 | .add("-acodec","copy") 155 | .add("-f","flv") 156 | .add("-y").add("rtmp://106.14.182.20:1935/rtmp/test2")); 157 | manager.start("test3", CommandBuidlerFactory.createBuidler() 158 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 159 | .add("-rtsp_transport","tcp") 160 | .add("-vcodec","copy") 161 | .add("-acodec","copy") 162 | .add("-f","flv") 163 | .add("-y").add("rtmp://106.14.182.20:1935/rtmp/test3")); 164 | manager.start("test4", CommandBuidlerFactory.createBuidler() 165 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 166 | .add("-rtsp_transport","tcp") 167 | .add("-vcodec","copy") 168 | .add("-acodec","copy") 169 | .add("-f","flv") 170 | .add("-y").add("rtmp://106.14.182.20:1935/rtmp/test4")); 171 | manager.start("test5", CommandBuidlerFactory.createBuidler() 172 | .add("ffmpeg").add("-i","rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov") 173 | // .add("-rtsp_transport","tcp") 174 | .add("-vcodec","copy") 175 | .add("-acodec","copy") 176 | .add("-f","flv") 177 | .add("-y").add("rtmp://106.14.182.20:1935/rtmp/test5")); 178 | Thread.sleep(30000); 179 | // 停止全部任务 180 | manager.stopAll(); 181 | manager.destory(); 182 | } 183 | 184 | public static void main(String[] args) throws InterruptedException { 185 | // test1(); 186 | // test2(); 187 | // test3(); 188 | // test4(); 189 | // testStreamCommandAssmbly(); 190 | // testBroken(); 191 | testBrokenMuti(); 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/util/CommonUtil.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.util; 2 | 3 | import java.io.File; 4 | import java.util.UUID; 5 | /** 6 | * 公共常用方法工具 7 | * @author eguid 8 | * 9 | */ 10 | public class CommonUtil { 11 | /** 12 | * 当前项目根路径 13 | */ 14 | public static final String rootPath = getProjectRootPath(); 15 | public static final String TRUE="true"; 16 | public static final String NULL_STRING=""; 17 | public static final String H_LINE="-"; 18 | public static String getUUID(){ 19 | return UUID.randomUUID().toString().trim().replaceAll(H_LINE, NULL_STRING); 20 | } 21 | /** 22 | * 是否为空 23 | * 24 | * @param str 25 | * @return boolean true:为空,false:不为空 26 | */ 27 | public static boolean isNull(String str) { 28 | return str == null || NULL_STRING.equals(str.trim()); 29 | } 30 | /** 31 | * 字符串是否是"true" 32 | * @param str 33 | * @return 34 | */ 35 | public static boolean isTrue(String str){ 36 | return TRUE.equals(str)?true:false; 37 | } 38 | 39 | /** 40 | * 获取项目根目录(静态) 41 | * @return 42 | */ 43 | public static String getRootPath() { 44 | return rootPath; 45 | } 46 | /** 47 | * 获取项目根目录(动态) 48 | * @return 49 | */ 50 | public static String getProjectRootPath() { 51 | String path=null; 52 | try{ 53 | path =CommonUtil.class.getResource("/").getPath(); 54 | }catch(Exception e){ 55 | File directory = new File(NULL_STRING); 56 | path= directory.getAbsolutePath()+File.separator; 57 | } 58 | return path; 59 | } 60 | /** 61 | * 获取类路径 62 | * @param cla 63 | * @return 64 | */ 65 | public static String getClassPath(Class cla){ 66 | return cla.getResource("").getPath(); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/util/ExecUtil.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.util; 2 | 3 | import java.io.IOException; 4 | 5 | import cc.eguid.commandManager.data.CommandTasker; 6 | import cc.eguid.commandManager.handler.OutHandler; 7 | import cc.eguid.commandManager.handler.OutHandlerMethod; 8 | 9 | /** 10 | * 命令行操作工具类 11 | * @author eguid 12 | * 13 | */ 14 | public class ExecUtil { 15 | 16 | /** 17 | * 执行命令行并获取进程 18 | * @param cmd 19 | * @return 20 | * @throws IOException 21 | */ 22 | public static Process exec(String cmd) throws IOException { 23 | Runtime runtime = Runtime.getRuntime(); 24 | Process process = runtime.exec(cmd);// 执行命令获取主进程 25 | return process; 26 | } 27 | 28 | /** 29 | * 销毁进程 30 | * @param process 31 | * @return 32 | */ 33 | public static boolean stop(Process process) { 34 | if (process != null) { 35 | process.destroy(); 36 | return true; 37 | } 38 | return false; 39 | } 40 | 41 | /** 42 | * 销毁输出线程 43 | * @param outHandler 44 | * @return 45 | */ 46 | public static boolean stop(Thread outHandler) { 47 | if (outHandler != null && outHandler.isAlive()) { 48 | outHandler.stop(); 49 | outHandler.destroy(); 50 | return true; 51 | } 52 | return false; 53 | } 54 | 55 | /** 56 | * 销毁 57 | * @param process 58 | * @param outHandler 59 | */ 60 | public static void stop(CommandTasker tasker) { 61 | if(tasker!=null) { 62 | stop(tasker.getThread()); 63 | stop(tasker.getProcess()); 64 | } 65 | } 66 | 67 | /** 68 | * 创建命令行任务 69 | * @param id 70 | * @param command 71 | * @return 72 | * @throws IOException 73 | */ 74 | public static CommandTasker createTasker(String id,String command,OutHandlerMethod ohm) throws IOException { 75 | // 执行本地命令获取任务主进程 76 | Process process=exec(command); 77 | // 创建输出线程 78 | OutHandler outHandler=OutHandler.create(process.getErrorStream(), id,ohm); 79 | 80 | CommandTasker tasker = new CommandTasker(id,command, process, outHandler); 81 | 82 | return tasker; 83 | } 84 | 85 | /** 86 | * 中断故障缘故重启 87 | * @param tasker 88 | * @return 89 | * @throws IOException 90 | */ 91 | public static CommandTasker restart(CommandTasker tasker) throws IOException { 92 | if(tasker!=null) { 93 | String id=tasker.getId(),command=tasker.getCommand(); 94 | OutHandlerMethod ohm=null; 95 | if(tasker.getThread()!=null) { 96 | ohm=tasker.getThread().getOhm(); 97 | } 98 | 99 | //安全销毁命令行进程和输出子线程 100 | stop(tasker); 101 | // 执行本地命令获取任务主进程 102 | Process process=exec(command); 103 | tasker.setProcess(process); 104 | // 创建输出线程 105 | OutHandler outHandler=OutHandler.create(process.getErrorStream(), id,ohm); 106 | tasker.setThread(outHandler); 107 | } 108 | return tasker; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/util/PropertiesUtil.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.util; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Properties; 11 | 12 | import java.util.Map.Entry; 13 | /** 14 | * properties配置文件读取 15 | * @author eguid 16 | * 17 | */ 18 | public class PropertiesUtil { 19 | /** 20 | * 加载properties配置文件并读取配置项 21 | * @param path 22 | * @param cl 23 | * @return 24 | */ 25 | @SuppressWarnings("unchecked") 26 | public static T load(String path, Class cl) { 27 | InputStream is = null; 28 | try { 29 | is = getInputStream(path); 30 | } catch (FileNotFoundException e) { 31 | //尝试从web目录读取 32 | String newpath=CommonUtil.getProjectRootPath()+path; 33 | System.err.println("尝试从web目录读取配置文件:"+newpath); 34 | try { 35 | is = getInputStream(newpath); 36 | System.err.println("web目录读取到配置文件:"+newpath); 37 | } catch (FileNotFoundException e1) { 38 | System.err.println("没找到配置文件,读取默认配置文件"); 39 | //尝试从jar包中读取默认配置文件 40 | ClassLoader classloader = Thread.currentThread().getContextClassLoader(); 41 | try { 42 | is = classloader.getResourceAsStream("cc/eguid/FFmpegCommandManager/config/defaultFFmpegConfig.properties"); 43 | System.err.println("读取默认配置文件:defaultFFmpegConfig.properties"); 44 | } catch (Exception e2) { 45 | System.err.println("没找到默认配置文件:defaultFFmpegConfig.properties"); 46 | return null; 47 | } 48 | } 49 | } 50 | if (is != null) { 51 | Properties pro = new Properties(); 52 | try { 53 | System.err.println("加载配置文件..."); 54 | pro.load(is); 55 | System.err.println("加载配置文件完毕"); 56 | return (T)load(pro, cl); 57 | } catch (IOException e) { 58 | System.err.println("加载配置文件失败"); 59 | return null; 60 | } 61 | 62 | } 63 | return null; 64 | } 65 | /** 66 | * 读取配置项并转换为对应对象 67 | * @param pro 68 | * @param cl 69 | * @return 70 | */ 71 | public static Object load(Properties pro, Class cl) { 72 | try { 73 | Map map = getMap(pro); 74 | System.err.println("读取的配置项:" + map); 75 | Object obj = ReflectUtil.mapToObj(map, cl); 76 | System.err.println("转换后的对象:" + obj); 77 | return obj; 78 | } catch (InstantiationException e) { 79 | System.err.println("加载配置文件失败"); 80 | return null; 81 | } catch (IllegalAccessException e) { 82 | System.err.println("加载配置文件失败"); 83 | return null; 84 | } catch (IllegalArgumentException e) { 85 | System.err.println("加载配置文件失败"); 86 | return null; 87 | } catch (InvocationTargetException e) { 88 | System.err.println("加载配置文件失败"); 89 | return null; 90 | } 91 | } 92 | /** 93 | * 获取对应文件路径下的文件流 94 | * @param path 95 | * @return 96 | * @throws FileNotFoundException 97 | */ 98 | public static InputStream getInputStream(String path) throws FileNotFoundException { 99 | return new FileInputStream(path); 100 | } 101 | /** 102 | * 根据路径获取properties的Map格式内容 103 | * @param path 104 | * @return 105 | */ 106 | public static Map getMap(String path){ 107 | Properties pro=new Properties(); 108 | try { 109 | pro.load(getInputStream(path)); 110 | return getMap(pro); 111 | } catch (IOException e) { 112 | return null; 113 | } 114 | } 115 | /** 116 | * 根据路径获取properties的Map格式内容 117 | * @param path 118 | * @param isRootPath -是否在项目根目录中 119 | * @return 120 | */ 121 | public static Map getMap(String path,boolean isRootPath){ 122 | return getMap(isRootPath?CommonUtil.getProjectRootPath()+path:path); 123 | } 124 | /** 125 | * Properties配置项转为Map 126 | * @param pro 127 | * @return 128 | */ 129 | public static Map getMap(Properties pro) { 130 | if (pro == null || pro.isEmpty() || pro.size() < 1) { 131 | return null; 132 | } 133 | Map map = new HashMap(); 134 | for (Entry en : pro.entrySet()) { 135 | String key = (String) en.getKey(); 136 | Object value = en.getValue(); 137 | map.put(key, value); 138 | } 139 | return map; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/cc/eguid/commandManager/util/ReflectUtil.java: -------------------------------------------------------------------------------- 1 | package cc.eguid.commandManager.util; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | import java.util.Map; 7 | 8 | /** 9 | * 反射操作工具 10 | * 11 | * @author eguid 12 | * 13 | */ 14 | public class ReflectUtil { 15 | 16 | public static final String SET = "set"; 17 | public static final String GET = "get"; 18 | 19 | public static Object mapToObj(Map map, Class oc) 20 | throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 21 | Method[] ms = oc.getDeclaredMethods(); 22 | if (ms == null || ms.length < 1) { 23 | return null; 24 | } 25 | Object obj = getObject(oc); 26 | for (Method m : ms) { 27 | String methodName = m.getName(); 28 | String fieldName = getMethodField(methodName, SET); 29 | Object value = map.get(fieldName); 30 | if (value != null) { 31 | setMethodValue(m, obj, typeConvert(value, m)); 32 | } 33 | } 34 | return obj; 35 | } 36 | 37 | public static Object typeConvert(Object obj, Method m) { 38 | return typeConvert(obj, m.getParameterTypes()[0].getName()); 39 | } 40 | 41 | public static Object typeConvert(Object obj, Field f) { 42 | return typeConvert(obj, f.getType().getName()); 43 | } 44 | /** 45 | * 基础数据转换 46 | * @param obj 47 | * @param typeName 48 | * @return 49 | */ 50 | public static Object typeConvert(Object obj, String typeName) { 51 | // 基础数据都可以转为String 52 | String str = String.valueOf(obj); 53 | if ("int".equals(typeName) || "java.lang.Integer".equals(typeName)) { 54 | return Integer.valueOf(str.trim()); 55 | } else if ("long".equals(typeName) || "java.lang.Long".equals(typeName)) { 56 | return Long.valueOf(str.trim()); 57 | } else if ("byte".equals(typeName) || "java.lang.Byte".equals(typeName)) { 58 | return Byte.valueOf(str.trim()); 59 | } else if ("short".equals(typeName) || "java.lang.Short".equals(typeName)) { 60 | return Short.valueOf(str.trim()); 61 | } else if ("float".equals(typeName) || "java.lang.Float".equals(typeName)) { 62 | return Float.valueOf(str.trim()); 63 | } else if ("double".equals(typeName) || "java.lang.Double".equals(typeName)) { 64 | return Double.valueOf(str.trim()); 65 | } else if ("boolean".equals(typeName) || "java.lang.Boolean".equals(typeName)) { 66 | return CommonUtil.TRUE.equals(str)?true:false; 67 | } else if ("char".equals(typeName) || "java.lang.Character".equals(typeName)) { 68 | return Character.valueOf(str.trim().charAt(0)); 69 | } else if ("java.lang.String".equals(typeName)) { 70 | return str; 71 | } 72 | return null; 73 | } 74 | 75 | public static Class getFieldType(Class cl, String fieldName) throws NoSuchFieldException, SecurityException { 76 | Field f = cl.getDeclaredField(fieldName); 77 | return f.getType(); 78 | } 79 | 80 | public static Field findField(Class cl, String fieldName) throws NoSuchFieldException, SecurityException { 81 | return cl.getDeclaredField(fieldName); 82 | } 83 | 84 | /** 85 | * 执行方法 86 | * 87 | * @param m 88 | * - 方法 89 | * @param obj 90 | * - 对象 91 | * @param value 92 | * - 参数 93 | * @throws IllegalAccessException 94 | * @throws IllegalArgumentException 95 | * @throws InvocationTargetException 96 | */ 97 | public static Object setMethodValue(Method m, Object obj, Object... value) 98 | throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { 99 | m.getParameterTypes(); 100 | return m.invoke(obj, value); 101 | } 102 | 103 | public static Object getFieldValue(Class obj, String FieldName) throws NoSuchFieldException, SecurityException { 104 | return obj.getDeclaredField(FieldName); 105 | } 106 | 107 | /** 108 | * 通过class实例化 109 | * 110 | * @param oc 111 | * @return 112 | * @throws InstantiationException 113 | * @throws IllegalAccessException 114 | */ 115 | public static Object getObject(Class oc) throws InstantiationException, IllegalAccessException { 116 | return oc.newInstance(); 117 | } 118 | 119 | /** 120 | * 获取方法字段 121 | * 122 | * @param methodName 123 | * @param prefix 124 | * @param lowercase 125 | * @return 126 | */ 127 | public static String getMethodField(String methodName, String prefix) { 128 | String m = null; 129 | if (prefix != null) { 130 | if (methodName.indexOf(prefix) >= 0) { 131 | m = methodName.substring(prefix.length()); 132 | return stringFirstLower(m); 133 | } 134 | } 135 | return m; 136 | } 137 | 138 | /** 139 | * 首字母大写 140 | * 141 | * @param str 142 | * @return 143 | */ 144 | public static String stringFirstUpper(String str) { 145 | char[] ch = str.toCharArray(); 146 | if (ch[0] >= 'a' && ch[0] <= 'z') { 147 | ch[0] = (char) (ch[0] - 32); 148 | } 149 | return new String(ch); 150 | } 151 | 152 | /** 153 | * 首字母小写 154 | * 155 | * @param str 156 | * @return 157 | */ 158 | public static String stringFirstLower(String str) { 159 | char[] ch = str.toCharArray(); 160 | if (ch[0] >= 'A' && ch[0] <= 'Z') { 161 | ch[0] = (char) (ch[0] + 32); 162 | } 163 | return new String(ch); 164 | } 165 | 166 | } 167 | -------------------------------------------------------------------------------- /src/loadFFmpeg.properties: -------------------------------------------------------------------------------- 1 | #ffmpeg执行路径,一般为ffmpeg的安装目录,该路径只能是目录,不能为具体文件路径,否则会报错 2 | path=E:/test/ffmpeg/bin/ 3 | #存放任务的默认Map的初始化大小 4 | size=10 5 | #事件回调通知接口地址 6 | callback=http://127.0.0.1/callback 7 | #网络超时设置(毫秒) 8 | timeout=300 9 | 10 | #开启保活线程 11 | keepalive=true 12 | 13 | #是否输出debug消息 14 | debug=true 15 | -------------------------------------------------------------------------------- /src/readme.md: -------------------------------------------------------------------------------- 1 | # 使用手册: 2 | 3 | ## 创建命令行管理器 4 | 5 | ``` 6 | //18.12.02新版本创建方式 7 | CommandManager manager=new CommandManagerImpl(10); 8 | 9 | //老版本创建方式: 10 | FFmpegManager manager=new FFmpegManagerImpl(10); 11 | //当然也可以这样 12 | FFmpegManager manager=new FFmpegManagerImpl();//这样会从配置文件中读取size的值作为初始化参数 13 | ``` 14 | ## 组装命令 15 | ``` 16 | Map map = new HashMap(); 17 | map.put("appName", "test123"); 18 | map.put("input","rtsp://admin:admin@192.168.2.236:37779/cam/realmonitor?channel=1&subtype=0"); 19 | map.put("output", "rtmp://192.168.30.21/live/"); 20 | map.put("codec","h264"); 21 | map.put("fmt", "flv"); 22 | map.put("fps", "25"); 23 | map.put("rs", "640x360"); 24 | map.put("twoPart","2"); 25 | ``` 26 | 27 | ## 执行任务,id就是appName,如果执行失败返回为null 28 | ``` 29 | String id=manager.start(map); 30 | System.out.println(id); 31 | ``` 32 | ## 通过id查询 33 | ``` 34 | TaskEntity info=manager.query(id); 35 | System.out.println(info); 36 | ``` 37 | ## 查询全部任务 38 | ``` 39 | Collection infoList=manager.queryAll(); 40 | System.out.println(infoList); 41 | ``` 42 | 43 | ## 停止id对应的任务 44 | ``` 45 | manager.stop(id); 46 | ``` 47 | ## 执行原生ffmpeg命令(不包含ffmpeg的执行路径,该路径会从配置文件中自动读取) 48 | ``` 49 | manager.start("test1", "ffmpeg -i input_file -vcodec copy -an output_file_video"); 50 | //包含完整ffmpeg执行路径的命令 51 | manager.start("test2,","d:/ffmpeg/ffmpeg -i input_file -vcodec copy -an output_file_video",true); 52 | ``` 53 | ## 停止全部任务 54 | ``` 55 | manager.stopAll(); 56 | ``` 57 | --------------------------------------------------------------------------------