VideoFileService.java
11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package top.panll.assist.service;
import com.alibaba.fastjson.JSON;
import net.bramp.ffmpeg.FFprobe;
import net.bramp.ffmpeg.probe.FFmpegProbeResult;
import net.bramp.ffmpeg.progress.Progress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import top.panll.assist.config.RedisUtil;
import top.panll.assist.dto.UserSettings;
import top.panll.assist.utils.DateUtils;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Service
public class VideoFileService {
private final static Logger logger = LoggerFactory.getLogger(VideoFileService.class);
@Autowired
private UserSettings userSettings;
@Autowired
private RedisUtil redisUtil;
@Autowired
private StringRedisTemplate stringRedisTemplate;
private ThreadPoolExecutor processThreadPool;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Bean("threadPoolExecutor")
private ThreadPoolExecutor iniThreadPool() {
int processThreadNum = Runtime.getRuntime().availableProcessors() * 10;
LinkedBlockingQueue<Runnable> processQueue = new LinkedBlockingQueue<Runnable>(10000);
processThreadPool = new ThreadPoolExecutor(processThreadNum,processThreadNum,
0L, TimeUnit.MILLISECONDS,processQueue,
new ThreadPoolExecutor.CallerRunsPolicy());
return processThreadPool;
}
public List<File> getAppList() {
File recordFile = new File(userSettings.getRecord());
if (recordFile != null) {
File[] files = recordFile.listFiles();
List<File> result = Arrays.asList(files);
Collections.sort(result);
return result;
}else {
return null;
}
}
public List<File> getStreamList(String app) {
File appFile = new File(userSettings.getRecord() + File.separator + app);
if (appFile != null) {
File[] files = appFile.listFiles();
List<File> result = Arrays.asList(files);
Collections.sort(result);
return result;
}else {
return null;
}
}
/**
* 对视频文件重命名, 00:00:00-00:00:00
* @param file
* @throws ParseException
*/
public void handFile(File file) throws ParseException {
FFprobe ffprobe = FFmpegExecUtils.getInstance().ffprobe;
if(file.isFile() && !file.getName().startsWith(".")&& file.getName().endsWith(".mp4") && file.getName().indexOf(":") < 0) {
try {
FFmpegProbeResult in = null;
in = ffprobe.probe(file.getAbsolutePath());
double duration = in.getFormat().duration * 1000;
String endTimeStr = file.getName().replace(".mp4", "");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
File dateFile = new File(file.getParent());
long startTime = formatter.parse(dateFile.getName() + " " + endTimeStr).getTime();
long durationLong = new Double(duration).longValue();
long endTime = startTime + durationLong;
endTime = endTime - endTime%1000;
String newName = file.getAbsolutePath().replace(file.getName(),
simpleDateFormat.format(startTime) + "-" + simpleDateFormat.format(endTime) + "-" + durationLong + ".mp4");
file.renameTo(new File(newName));
System.out.println(newName);
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
public List<Map<String, String>> getList() {
List<Map<String, String>> result = new ArrayList<>();
List<File> appList = getAppList();
if (appList != null && appList.size() > 0) {
for (File appFile : appList) {
List<File> streamList = getStreamList(appFile.getName());
if (streamList != null && streamList.size() > 0) {
for (File streamFile : streamList) {
Map<String, String> data = new HashMap<>();
data.put("app", appFile.getName());
data.put("stream", streamFile.getName());
// BasicFileAttributes bAttributes = null;
// try {
// bAttributes = Files.readAttributes(streamFile.toPath(),
// BasicFileAttributes.class);
// } catch (IOException e) {
// e.printStackTrace();
// }
// data.put("time", simpleDateFormat.format(new Date(bAttributes.lastModifiedTime().toMillis())));
result.add(data);
}
}
}
}
return result;
}
/**
* 获取制定推流的指定时间段内的推流
* @param app
* @param stream
* @param startTime
* @param endTime
* @return
*/
public List<File> getFilesInTime(String app, String stream, Date startTime, Date endTime){
List<File> result = new ArrayList<>();
if (app == null || stream == null) {
return result;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat formatterForDate = new SimpleDateFormat("yyyy-MM-dd");
String startTimeStr = formatter.format(startTime);
String endTimeStr = formatter.format(endTime);
logger.debug("获取[app: {}, stream: {}, statime: {}, endTime: {}]的视频", app, stream,
startTimeStr, endTimeStr);
File recordFile = new File(userSettings.getRecord());
File streamFile = new File(recordFile.getAbsolutePath() + File.separator + app + File.separator + stream);
if (!streamFile.exists()) {
logger.warn("获取[app: {}, stream: {}, statime: {}, endTime: {}]的视频时未找到目录: {}", app, stream,
startTimeStr, endTimeStr, stream);
return result;
}
File[] dateFiles = streamFile.listFiles((File dir, String name) -> {
Date fileDate = null;
try {
fileDate = formatterForDate.parse(name);
} catch (ParseException e) {
logger.error("过滤日期文件时异常: {}-{}", name, e.getMessage());
return false;
}
return (DateUtils.getStartOfDay(fileDate).compareTo(startTime) >= 0
&& DateUtils.getStartOfDay(fileDate).compareTo(endTime) <= 0) ;
});
if (dateFiles != null && dateFiles.length > 0) {
for (File dateFile : dateFiles) {
// TODO 按时间获取文件
File[] files = dateFile.listFiles((File dir, String name) ->{
boolean filterResult = false;
if (name.contains(":") && name.endsWith(".mp4") && !name.startsWith(".")){
String[] timeArray = name.split("-");
if (timeArray.length == 3){
String fileStartTimeStr = dateFile.getName() + " " + timeArray[0];
String fileEndTimeStr = dateFile.getName() + " " + timeArray[1];
try {
filterResult = formatter.parse(fileStartTimeStr).after(startTime) && formatter.parse(fileEndTimeStr).before(endTime);
} catch (ParseException e) {
logger.error("过滤视频文件时异常: {}-{}", name, e.getMessage());
return false;
}
}
}
return filterResult;
});
List<File> fileList = Arrays.asList(files);
result.addAll(fileList);
}
}
if (result.size() > 0) {
result.sort((File f1, File f2) -> {
int sortResult = 0;
String[] timeArray1 = f1.getName().split("-");
String[] timeArray2 = f2.getName().split("-");
if (timeArray1.length == 3 && timeArray2.length == 3){
File dateFile1 = f1.getParentFile();
File dateFile2 = f2.getParentFile();
String fileStartTimeStr1 = dateFile1.getName() + " " + timeArray1[0];
String fileStartTimeStr2 = dateFile2.getName() + " " + timeArray2[0];
try {
sortResult = formatter.parse(fileStartTimeStr1).compareTo(formatter.parse(fileStartTimeStr2));
} catch (ParseException e) {
e.printStackTrace();
}
}
return sortResult;
});
}
return result;
}
public String mergeOrCut(String app, String stream, Date startTime, Date endTime) {
List<File> filesInTime = this.getFilesInTime(app, stream, startTime, endTime);
File recordFile = new File(new File(userSettings.getRecord()).getParentFile().getAbsolutePath() + File.separator + "recordTemp");
if (!recordFile.exists()) recordFile.mkdirs();
String temp = DigestUtils.md5DigestAsHex(String.valueOf(System.currentTimeMillis()).getBytes());
processThreadPool.execute(() -> {
FFmpegExecUtils.getInstance().mergeOrCutFile(filesInTime, recordFile, temp, (String status, double percentage, String result)->{
Map<String, String> data = new HashMap<>();
data.put("id", temp);
// 发出redis通知
if (status.equals(Progress.Status.END.name())) {
data.put("percentage", "1");
data.put("recordFile", result);
redisUtil.set(app + "_" + stream + "_" + temp, data, 3*60*60);
stringRedisTemplate.convertAndSend("topic_mergeorcut_end", JSON.toJSONString(data));
}else {
data.put("percentage", percentage + "");
redisUtil.set(app + "_" + stream + "_" + temp, data, 3*60*60);
stringRedisTemplate.convertAndSend("topic_mergeorcut_continue", JSON.toJSONString(data));
}
});
});
return temp;
}
public List<File> getDateList(String app, String stream) {
File recordFile = new File(userSettings.getRecord());
File streamFile = new File(recordFile.getAbsolutePath() + File.separator + app + File.separator + stream);
if (!streamFile.exists()) {
logger.warn("获取[app: {}, stream: {}]的视频时未找到目录: {}", app, stream, stream);
return null;
}
File[] dateFiles = streamFile.listFiles();
List<File> dateFileList = Arrays.asList(dateFiles);
dateFileList.sort((File f1, File f2)->{
int sortResult = 0;
SimpleDateFormat formatterForDate = new SimpleDateFormat("yyyy-MM-dd");
try {
sortResult = formatterForDate.parse(f1.getName()).compareTo(formatterForDate.parse(f2.getName()));
} catch (ParseException e) {
e.printStackTrace();
}
return sortResult;
});
return dateFileList;
}
}