AdminVideoApiController.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. package com.goafanti.admin.controller;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.math.BigInteger;
  12. import java.nio.channels.FileChannel;
  13. import java.security.MessageDigest;
  14. import java.security.NoSuchAlgorithmException;
  15. import java.util.Base64;
  16. import java.util.Calendar;
  17. import java.util.concurrent.Callable;
  18. import java.util.concurrent.ExecutionException;
  19. import java.util.concurrent.ExecutorService;
  20. import java.util.concurrent.Executors;
  21. import java.util.concurrent.FutureTask;
  22. import java.util.concurrent.TimeUnit;
  23. import javax.annotation.Resource;
  24. import javax.servlet.http.HttpServletRequest;
  25. import javax.validation.Valid;
  26. import net.bramp.ffmpeg.FFmpeg;
  27. import net.bramp.ffmpeg.FFmpegExecutor;
  28. import net.bramp.ffmpeg.FFmpegUtils;
  29. import net.bramp.ffmpeg.FFprobe;
  30. import net.bramp.ffmpeg.builder.FFmpegBuilder;
  31. import net.bramp.ffmpeg.job.FFmpegJob;
  32. import net.bramp.ffmpeg.probe.FFmpegProbeResult;
  33. import net.bramp.ffmpeg.progress.Progress;
  34. import net.bramp.ffmpeg.progress.ProgressListener;
  35. import org.springframework.beans.factory.annotation.Value;
  36. import org.springframework.stereotype.Controller;
  37. import org.springframework.validation.BindingResult;
  38. import org.springframework.web.bind.annotation.RequestMapping;
  39. import org.springframework.web.bind.annotation.RequestMethod;
  40. import org.springframework.web.bind.annotation.ResponseBody;
  41. import com.goafanti.admin.service.AdminVideoService;
  42. import com.goafanti.common.bo.Result;
  43. import com.goafanti.common.constant.ErrorConstants;
  44. import com.goafanti.common.controller.CertifyApiController;
  45. import com.goafanti.common.enums.AttachmentType;
  46. import com.goafanti.common.enums.VideoFields;
  47. import com.goafanti.common.model.JtVideo;
  48. import com.goafanti.common.utils.StringUtils;
  49. import com.goafanti.core.shiro.token.TokenManager;
  50. @Controller
  51. @RequestMapping(value = "/api/admin/video")
  52. public class AdminVideoApiController extends CertifyApiController {
  53. @Resource
  54. private AdminVideoService adminVideoService;
  55. @Value(value = "${ffmpeg.path}")
  56. private String ffmpegPath = null;
  57. @Value(value = "${ffprobe.path}")
  58. private String ffprobePath = null;
  59. @Value(value = "${video.temppath}")
  60. private String videoTemppath = null;
  61. // 上传视频只做MP4格式的
  62. @RequestMapping(value = "/upload", method = RequestMethod.POST)
  63. @ResponseBody
  64. public Result uploadPicture(HttpServletRequest req, String sign) {
  65. Result res = new Result();
  66. AttachmentType attachmentType = AttachmentType.getField(sign);
  67. if (attachmentType == AttachmentType.VIDEO) {
  68. // 先将视频存在本地文件中
  69. String dir = videoTemppath + "/convert_before";
  70. String filename = handleVideoFiles(res, req, dir);
  71. res.setData(filename);
  72. } else if (attachmentType == AttachmentType.VIDEO_COVER) {
  73. String picturebase = req.getParameter("picturebase");
  74. String filename = req.getParameter("filename");
  75. byte[] bs = Base64.getDecoder().decode(picturebase);
  76. filename = System.nanoTime()
  77. + filename.substring(filename.indexOf("."));
  78. res.setData(handleBaseFiles(res, "/video_cover/", false, bs, sign,
  79. TokenManager.getUserId(), filename));
  80. } else {
  81. res.getError().add(
  82. buildError(ErrorConstants.PARAM_ERROR, "", "文件标示"));
  83. }
  84. return res;
  85. }
  86. private String createFileName() {
  87. // 年月日
  88. Calendar now = Calendar.getInstance();
  89. int year = now.get(Calendar.YEAR);
  90. int month = now.get(Calendar.MONTH) + 1;
  91. int day = now.get(Calendar.DAY_OF_MONTH);
  92. String dir = "/" + year + "/" + month + "/" + day;
  93. return dir;
  94. }
  95. // 查看所有视频信息
  96. @RequestMapping(value = "/getVideoList", method = RequestMethod.GET)
  97. @ResponseBody
  98. public Result getVideoList(JtVideo video, Integer pageNo, Integer pageSize) {
  99. Result result = new Result();
  100. result.setData(adminVideoService.getVideoList(video, pageNo, pageSize,1));
  101. return result;
  102. }
  103. // 查看单个信息
  104. @RequestMapping(value = "/getVideoById", method = RequestMethod.GET)
  105. @ResponseBody
  106. public Result getVideoById(String id) {
  107. Result result = new Result();
  108. JtVideo video = new JtVideo();
  109. video.setId(id);
  110. result.setData(adminVideoService.getVideoById(video));
  111. return result;
  112. }
  113. // 新增视频信息
  114. @RequestMapping(value = "/insertVideo", method = RequestMethod.POST)
  115. @ResponseBody
  116. public Result insertVideo(@Valid JtVideo video , BindingResult bindingResult) throws IOException,
  117. InterruptedException, ExecutionException {
  118. // 数据限制
  119. Result result = new Result();
  120. if (bindingResult.hasErrors()) {
  121. result.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
  122. VideoFields.getFieldDesc(bindingResult.getFieldError().getField())));
  123. return result;
  124. }
  125. if(StringUtils.isBlank(video.getName())){
  126. result.getError().add(
  127. buildError( "视频名称不能是空", "视频名称不能是空"));
  128. return result;
  129. }
  130. //名称重名限制
  131. if(adminVideoService.nameCheck(video.getName().trim()) > 0){
  132. result.getError().add(
  133. buildError(ErrorConstants.PARAM_ERROR, "", "视频名称重复不能新增"));
  134. return result;
  135. }
  136. String filename = video.getUrl();
  137. // 生成保存到数据库的url
  138. String output = System.nanoTime() + ".mp4";
  139. String filepath = createFileName();
  140. video.setUrl(filepath + "/" + output);
  141. video.setTranscoding(1);
  142. // 保存到数据库
  143. result.setData(adminVideoService.insertVideo(video));
  144. // 压缩视频并将视频存储
  145. FileChannel fc= null;
  146. try {
  147. File f= new File(filename);
  148. if (f.exists() && f.isFile()){
  149. FileInputStream fis= new FileInputStream(f);
  150. fc= fis.getChannel();
  151. Long fsize = fc.size()/1024/1024;
  152. System.out.println(fc.size());
  153. if(fsize.longValue() > 50){
  154. videoChange(filename, output, video.getUrl(), videoTemppath + "/convert_after" + filepath );
  155. }else{
  156. copy(filename, output, videoTemppath + "/convert_after" + filepath + "/" );
  157. //修改数据库
  158. updateSql(video.getUrl(), videoTemppath + "/convert_after" + filepath ,output);
  159. }
  160. }else{
  161. System.out.println("file doesn't exist or is not a file");
  162. }
  163. } catch (FileNotFoundException e) {
  164. System.out.println(e);
  165. } catch (IOException e) {
  166. System.out.println(e);
  167. } finally {
  168. if (null!=fc){
  169. try{
  170. fc.close();
  171. }catch(IOException e){
  172. System.out.println(e);
  173. }
  174. }
  175. }
  176. return result;
  177. }
  178. // 修改视频
  179. @RequestMapping(value = "/updateVideo", method = RequestMethod.POST)
  180. @ResponseBody
  181. public Result updateVideo(@Valid JtVideo video , BindingResult bindingResult) throws IOException,
  182. InterruptedException, ExecutionException {
  183. Result result = new Result();
  184. if (bindingResult.hasErrors()) {
  185. result.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
  186. VideoFields.getFieldDesc(bindingResult.getFieldError().getField())));
  187. return result;
  188. }
  189. JtVideo v = new JtVideo();
  190. v.setId(video.getId());
  191. JtVideo oldVideo = adminVideoService.getVideoById(v);
  192. if (StringUtils.isBlank(video.getId())) {
  193. result.getError().add(
  194. buildError(ErrorConstants.PARAM_ERROR, "", "视频id不能为空"));
  195. return result;
  196. } else if (null == oldVideo) {
  197. result.getError().add(
  198. buildError(ErrorConstants.PARAM_ERROR, "", "视频id不存在"));
  199. return result;
  200. }
  201. if(null != video.getName() && "".equals(video.getName().trim())){
  202. result.getError().add(
  203. buildError( "视频名称不能是空", "视频名称不能是空"));
  204. return result;
  205. }
  206. //如果是删除视频
  207. if(null != video.getStatus() && video.getStatus() == 3){
  208. if(oldVideo.getStatus() == 1){
  209. result.getError().add(
  210. buildError( "视频已经发布不能删除", "视频已经发布不能删除"));
  211. return result;
  212. }else{
  213. deleteFtpVideo( videoTemppath + "/convert_after" + oldVideo.getUrl());
  214. }
  215. }
  216. Boolean flag = false;
  217. String filepath = "";
  218. String output = "";
  219. if (StringUtils.isNotBlank(video.getUrl()) && !video.getUrl().equals(oldVideo.getUrl())) { // 如果修改了视频
  220. video.setTranscoding(1);
  221. // 压缩视频并将视频
  222. String filename = video.getUrl();
  223. output = System.nanoTime() + ".mp4";
  224. filepath = createFileName() ;
  225. video.setUrl(filepath + "/" + output);
  226. FileChannel fc= null;
  227. try {
  228. File f= new File(filename);
  229. if (f.exists() && f.isFile()){
  230. FileInputStream fis= new FileInputStream(f);
  231. fc= fis.getChannel();
  232. Long fsize = fc.size()/1024/1024;
  233. System.out.println(fc.size());
  234. if(fsize.longValue() > 50){
  235. videoChange(filename, output, video.getUrl(), videoTemppath + "/convert_after" + filepath );
  236. }else{
  237. copy(filename, output, videoTemppath + "/convert_after" + filepath + "/" );
  238. flag = true;
  239. }
  240. }else{
  241. System.out.println("file doesn't exist or is not a file");
  242. }
  243. } catch (FileNotFoundException e) {
  244. System.out.println(e);
  245. } catch (IOException e) {
  246. System.out.println(e);
  247. } finally {
  248. if (null!=fc){
  249. try{
  250. fc.close();
  251. }catch(IOException e){
  252. System.out.println(e);
  253. }
  254. }
  255. }
  256. // videoChange(filename, output, video.getUrl(), videoTemppath + "/convert_after" + filepath);
  257. //删除原来远程的视频
  258. deleteFtpVideo(videoTemppath + "/convert_after" + oldVideo.getUrl());
  259. }else{
  260. video.setUrl(null);
  261. }
  262. result.setData(adminVideoService.updateVideo(video));
  263. if(flag){
  264. updateSql(video.getUrl(), videoTemppath + "/convert_after" + filepath ,output);
  265. }
  266. return result;
  267. }
  268. private Boolean deleteFtpVideo(String url){
  269. boolean b = false;
  270. //判断文件是否存在
  271. File f= new File(url);
  272. if(f.exists()){
  273. System.out.println("+++++++++++++++++++++++++++++文件存在,删除视频"+url);
  274. b = f.delete();
  275. }
  276. return b;
  277. }
  278. // 将文件转码
  279. private String videoChange(String input, String output, String url,String outputdir) throws IOException,
  280. InterruptedException, ExecutionException {
  281. File file = new File(outputdir);
  282. if(!file.isDirectory()){
  283. file.mkdirs();//创建文件夹
  284. }
  285. FFmpeg ffmpeg = new FFmpeg(ffmpegPath);
  286. FFprobe ffprobe = new FFprobe(ffprobePath);
  287. FFmpegProbeResult in = ffprobe.probe(input);
  288. FFmpegBuilder builder = new FFmpegBuilder();
  289. builder.setInput(in) // 输入文件
  290. .overrideOutputFiles(true) // 覆盖重复文件
  291. .addOutput(outputdir + "/" + output) // 输出文件
  292. .setFormat("mp4") // 设置格式
  293. .setTargetSize(250_000) // 目标大小
  294. .disableSubtitle() // 没有子标题
  295. .setAudioChannels(1) // 声道
  296. .setAudioSampleRate(48_000) // 音频采样率
  297. .setAudioBitRate(32768) // 音频传输率
  298. .setVideoCodec("libx264") // 视频编解码器
  299. .setVideoFrameRate(24, 1) // 视频帧速率
  300. .setVideoResolution(640, 480) // 视频分辨率
  301. .setStrict(FFmpegBuilder.Strict.EXPERIMENTAL) // 严格形式
  302. .done();
  303. FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);
  304. ExecutorService service = Executors.newCachedThreadPool();
  305. // 3.直接new一个FutureTask
  306. SubTask subTask = new SubTask(executor, builder, in, url, input, output, outputdir);
  307. FutureTask<Boolean> result = new FutureTask<Boolean>(subTask);
  308. // 4.提交任务
  309. service.submit(result);
  310. // 5.关闭线程池
  311. service.shutdown();
  312. // LOGGER.info("=============返回给前端=============");
  313. //System.out.println("task运行结果" + result.get());
  314. return "SUCESS";
  315. }
  316. private void updateSql(String url, String tempdir, String filename) {
  317. // 修改数据
  318. File file = new File(tempdir+"/"+filename);
  319. JtVideo video = new JtVideo();
  320. video.setMd5(FileMD5(file));
  321. video.setTranscoding(2);
  322. video.setUrl(url);
  323. url = url.substring(0,url.lastIndexOf("/"));
  324. System.out.println("修改数据库000000000000000000000"+url);
  325. adminVideoService.updateByUrl(video);//修改状态
  326. }
  327. // 获得文件md5
  328. private String FileMD5(File file) {
  329. try {
  330. FileInputStream fis = new FileInputStream(file);
  331. MessageDigest md = MessageDigest.getInstance("MD5");
  332. byte[] buffer = new byte[1024];
  333. int length = -1;
  334. while ((length = fis.read(buffer, 0, 1024)) != -1) {
  335. md.update(buffer, 0, length);
  336. }
  337. BigInteger bigInt = new BigInteger(1, md.digest());
  338. return bigInt.toString(16);
  339. } catch (FileNotFoundException e) {
  340. e.printStackTrace();
  341. } catch (NoSuchAlgorithmException e) {
  342. e.printStackTrace();
  343. } catch (IOException e) {
  344. e.printStackTrace();
  345. }
  346. return null;
  347. }
  348. class SubTask implements Callable<Boolean> {
  349. private Boolean state = false;
  350. private FFmpegExecutor executor;
  351. private FFmpegBuilder builder;
  352. private FFmpegProbeResult probeResult;
  353. private String url;
  354. private String input;
  355. private String output;
  356. private String tempdir;
  357. public SubTask(FFmpegExecutor executor, FFmpegBuilder builder,
  358. FFmpegProbeResult probeResult, String url, String input,
  359. String output, String tempdir) {
  360. this.executor = executor;
  361. this.builder = builder;
  362. this.probeResult = probeResult;
  363. this.url = url;
  364. this.input = input;
  365. this.output = output;
  366. this.tempdir = tempdir;
  367. }
  368. public FFmpegExecutor getExecutor() {
  369. return executor;
  370. }
  371. public FFmpegBuilder getBuilder() {
  372. return builder;
  373. }
  374. public String getUrl() {
  375. return url;
  376. }
  377. public String getInput() {
  378. return input;
  379. }
  380. public String getOutput() {
  381. return output;
  382. }
  383. public Boolean getState() {
  384. return state;
  385. }
  386. @Override
  387. public Boolean call() throws Exception {
  388. final double duration_ns = probeResult.getFormat().duration
  389. * TimeUnit.SECONDS.toNanos(1);
  390. try {
  391. FFmpegJob job = executor.createJob(builder,
  392. new ProgressListener() {
  393. @Override
  394. public void progress(Progress progress) {
  395. double percentage = progress.out_time_ns
  396. / duration_ns;
  397. System.out.println(String
  398. .format("[%.0f%%] status:%s frame:%d time:%s ms fps:%.0f speed:%.2fx",
  399. percentage * 100,
  400. progress.status,
  401. progress.frame,
  402. FFmpegUtils.toTimecode(
  403. progress.out_time_ns,
  404. TimeUnit.NANOSECONDS),
  405. progress.fps.doubleValue(),
  406. progress.speed));
  407. }
  408. });
  409. job.run();
  410. // 6.阻塞 call
  411. // System.out.println("设置 sate");
  412. // latch.wait();
  413. state = true;
  414. updateSql(url, tempdir,output);
  415. // 删除未压缩的视频
  416. File f1 = new File(input);
  417. f1.delete();
  418. } catch (Exception e) {
  419. e.printStackTrace();
  420. }
  421. return state;
  422. }
  423. }
  424. public static void copy(String file1, String file2, String dir) {
  425. File file = new File(dir);
  426. if(!file.isDirectory()){
  427. file.mkdirs();//创建文件夹
  428. }
  429. System.out.println(file1);
  430. System.out.println(file2);
  431. File src = new File(file1);
  432. InputStream in = null;
  433. OutputStream out = null;
  434. System.out.println(file1.substring(file1.lastIndexOf("/"),file1.length()));//获取单个文件的源文件的名称
  435. try {
  436. in = new BufferedInputStream(new FileInputStream(src), 16 * 1024);
  437. FileOutputStream f = new FileOutputStream(dir+file2);// 一定要加上文件名称
  438. out = new BufferedOutputStream(f, 16 * 1024);
  439. byte[] buffer = new byte[16 * 1024];
  440. int len = 0;
  441. while ((len = in.read(buffer)) > 0) {
  442. out.write(buffer, 0, len);
  443. }
  444. } catch (Exception e) {
  445. e.printStackTrace();
  446. } finally {
  447. if (null != in) {
  448. try {
  449. in.close();
  450. } catch (IOException e) {
  451. e.printStackTrace();
  452. }
  453. }
  454. if (null != out) {
  455. try {
  456. out.close();
  457. } catch (IOException e) {
  458. e.printStackTrace();
  459. }
  460. }
  461. }
  462. }
  463. public static void main(String[] args) {
  464. copy("D:/Downloads/环保小视频.mp4","haha.mp4","F:/data/local/video/convert_after/2018/11/9/");
  465. }
  466. }