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
package com.yanzuoguang.media;
import com.yanzuoguang.util.helper.HttpHelper;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.thread.ThreadHelper;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* m3mu文件下载
*
* @author 颜佐光
*/
public class HlsDownloader {
/**
* 匹配ts文件
*/
private static final Pattern pattern = Pattern.compile(".*ts");
/**
* 源地址
*/
private String serverUrl = StringHelper.EMPTY;
/**
*
*/
private String localUrl = StringHelper.EMPTY;
/**
* 线程数量
*/
private int threadCount;
/**
* 下载ts的文件数量
*/
private int maxTs;
/**
* 服务器url路径
*/
private String tempServerPath;
public HlsDownloader(String serverUrl, String localUrl) {
this(serverUrl, localUrl, 5, -1);
}
public HlsDownloader(String serverUrl, String localUrl, int threadCount, int maxTs) {
if (StringHelper.isEmpty(localUrl)) {
return;
}
this.serverUrl = serverUrl;
this.localUrl = localUrl;
this.threadCount = threadCount;
this.maxTs = maxTs;
}
/**
* 开启下载
*
* @param isAsync 是否异步下载
* @param removeTs 删除ts临时文件
* @return
* @throws Exception
*/
public String download(boolean isAsync, boolean removeTs) throws Exception {
// 处理临时服务器路径
tempServerPath = StringHelper.left(this.serverUrl, this.serverUrl.length() - new File(this.serverUrl).getName().length());
// 用于判断url是否已经存在
HashMap<String, Integer> urlHas = new HashMap<>();
// 待下载的数组
HashMap<Integer, String> waitDown = new HashMap<>();
// 已下载数组文件列表
HashMap<Integer, String> hasDown = new HashMap<>();
// 开启线程
if (isAsync) {
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 循环下载
while (isDown(hasDown)) {
// 下载片段
downLoadIndexFile(waitDown, hasDown, hasDown.size());
// 等到100ms
if (waitDown.isEmpty()) {
ThreadHelper.sleep(100);
}
}
}
});
thread.start();
}
}
do {
// 添加m3mu到待下载目录
addWaitDown(urlHas, waitDown, hasDown);
// 同步或者异步下载
if (isAsync) {
// 等待500毫秒
Thread.sleep(500);
} else {
downLoadIndexFile(waitDown, hasDown, hasDown.size());
}
} while (isDown(hasDown));
// 组合下载的ts文件为视频
composeFile(hasDown, removeTs);
// 下载后的本地文件地址
return this.localUrl;
}
private boolean isDown(HashMap<Integer, String> hasDown) {
return hasDown.size() <= this.maxTs || this.maxTs < 0;
}
/**
* 添加m3mu到待下载目录
*
* @param urlPos 用于判断url是否已经存在
* @param waitDown 待下载的数组
* @param hasDown 已下载数组文件列表
* @throws MalformedURLException
*/
private void addWaitDown(HashMap<String, Integer> urlPos, HashMap<Integer, String> waitDown, HashMap<Integer, String> hasDown) throws MalformedURLException {
// 当没有需要下载的时候,则继续读取列表下载
if (waitDown.isEmpty()) {
// 解析的索引文件内容
String m3muTsList = getIndexFile();
// 解析成 *.ts 的文件列表
List<String> urlList = analysisIndex(m3muTsList);
// 添加到待下载目录中
for (int i = 0; i < urlList.size(); i++) {
String url = urlList.get(i);
// 处理url
url = tempServerPath + url;
// 判断url是否存在
if (urlPos.containsKey(url)) {
continue;
}
// 已经下载的ts包含的url数量
int totalSize = waitDown.size() + hasDown.size();
// 写入url
urlPos.put(url, totalSize);
waitDown.put(totalSize, url);
}
}
}
/**
* 下载索引文件
*
* @return 返回索引文件的呢日哦嗯
* @throws Exception
*/
private String getIndexFile() throws MalformedURLException {
StringBuilder content = new StringBuilder();
URL url = new URL(this.serverUrl);
//下载资源
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = in.readLine()) != null) {
content.append(line);
content.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
/**
* 解析索引文件
*
* @param content m3mu文件内容
* @return
* @throws Exception
*/
private List<String> analysisIndex(String content) {
List<String> list = new ArrayList<String>();
Matcher ma = pattern.matcher(content);
while (ma.find()) {
list.add(ma.group());
}
return list;
}
/**
* 下载视频片段
*
* @return
*/
private void downLoadIndexFile(HashMap<Integer, String> waitDown, HashMap<Integer, String> hasDown, int pos) {
// 获取源文件地址
String serverTsUrl;
synchronized (waitDown) {
serverTsUrl = waitDown.remove(pos);
}
if (StringHelper.isEmpty(serverTsUrl)) {
return;
}
// 写入生成地址到文件列表
try {
// 获取生成的地址
String localTs = this.localUrl + "." + pos + ".ts";
// 设置文件下载成功
hasDown.put(pos, localTs);
// 下载服务器文件
HttpHelper.downToLocal(serverTsUrl, localTs);
} catch (Exception e) {
// 判断文件是否下载失败
e.printStackTrace();
}
}
/**
* 视频片段合成
*
* @param hasDown 已经下载的文件段列表
* @return
* @throws Exception
*/
private void composeFile(HashMap<Integer, String> hasDown, boolean removeTs) throws Exception {
if (hasDown.isEmpty()) {
return;
}
File fileTo = new File(this.localUrl);
if (hasDown.size() == 1 && removeTs) {
// 获取第一个 ts 文件
File file = new File(hasDown.get(0));
file.renameTo(fileTo);
} else {
// 订单输出文件流
try (FileOutputStream fileOutputStream = new FileOutputStream(fileTo)) {
// 遍历已经下载的ts文件
for (int i = 0; i < hasDown.size(); i++) {
// 获取 ts 文件
File file = new File(hasDown.get(i));
if (!file.exists()) {
continue;
}
// 读取文件
try (FileInputStream fis = new FileInputStream(file)) {
// 定义文件缓存
byte[] bytes = new byte[1024];
// 读取的文件长度
int length = 0;
// 读取来源文件
while ((length = fis.read(bytes)) != -1) {
// 写入目标文件
fileOutputStream.write(bytes, 0, length);
}
}
// 删除ts文件
if (removeTs) {
file.delete();
}
}
}
}
}
}