需要扩展框架以支持M3U8文件下载。M3U8是HTTP Live Streaming (HLS)协议使用的文件格式,是一种用于流媒体的文件列表格式。

M3U8文件下载的特点:

  1. M3U8文件本身是一个索引文件,包含了多个.ts分片文件的URL
  2. 需要先下载M3U8文件,解析其中的内容,获取所有的分片URL
  3. 然后依次或并行下载所有的.ts分片
  4. 最后将所有分片合并成一个完整的媒体文件

我需要设计以下内容:

  1. M3U8文件解析器,用于解析M3U8文件格式并提取分片URL
  2. 分片下载管理器,用于管理所有分片的下载状态
  3. 分片合并器,用于将所有分片合并成完整媒体文件

我会基于之前设计的下载框架,扩展一个专门用于M3U8下载的功能模块。

扩展下载框架,支持M3U8文件下载

下面是针对M3U8文件下载的功能扩展,可以集成到之前的下载框架中:

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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// M3U8DownloadManager.kt

import kotlinx.coroutines.*
import okhttp3.*
import okio.buffer
import okio.sink
import okio.source
import java.io.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.regex.Pattern
import java.net.URL

/**
* M3U8文件解析器
*/
class M3U8Parser {
// M3U8文件信息
data class M3U8Info(
val masterUrl: String, // 主M3U8 URL
val baseUrl: String, // 基础URL
val duration: Float = 0f, // 总时长(秒)
val segmentList: List<M3U8Segment> // 分片列表
)

// 分片信息
data class M3U8Segment(
val url: String, // 分片URL
val duration: Float, // 分片时长(秒)
val index: Int, // 分片索引
var tsFilePath: String = "" // 本地保存路径
)

// 解析M3U8文件
suspend fun parse(url: String, client: OkHttpClient): M3U8Info = withContext(Dispatchers.IO) {
// 发送请求获取M3U8内容
val request = Request.Builder()
.url(url)
.build()

val response = client.newCall(request).execute()
if (!response.isSuccessful) {
throw IOException("Failed to fetch M3U8 file: ${response.code}")
}

val content = response.body?.string() ?: throw IOException("Empty M3U8 content")

// 判断是否是主播放列表
if (content.contains("#EXT-X-STREAM-INF")) {
return@withContext parseMainPlaylist(url, content, client)
} else {
return@withContext parseMediaPlaylist(url, content)
}
}

// 解析主播放列表
private suspend fun parseMainPlaylist(masterUrl: String, content: String, client: OkHttpClient): M3U8Info = withContext(Dispatchers.IO) {
// 提取带宽最高的子播放列表
val lines = content.split("\n")
var maxBandwidth = 0
var selectedUrl = ""

for (i in lines.indices) {
val line = lines[i]
if (line.startsWith("#EXT-X-STREAM-INF")) {
// 提取带宽参数
val bandwidthPattern = Pattern.compile("BANDWIDTH=(\\d+)")
val matcher = bandwidthPattern.matcher(line)
if (matcher.find()) {
val bandwidth = matcher.group(1).toInt()
if (bandwidth > maxBandwidth) {
maxBandwidth = bandwidth
// 下一行应该是URL
if (i + 1 < lines.size) {
val urlLine = lines[i + 1].trim()
if (!urlLine.startsWith("#")) {
selectedUrl = urlLine
}
}
}
}
}
}

// 如果URL是相对路径,转换为完整URL
val fullUrl = if (selectedUrl.startsWith("http")) {
selectedUrl
} else {
val baseUrl = URL(masterUrl)
val path = if (selectedUrl.startsWith("/")) {
selectedUrl
} else {
val masterPath = baseUrl.path
val lastSlash = masterPath.lastIndexOf('/')
if (lastSlash != -1) {
masterPath.substring(0, lastSlash + 1) + selectedUrl
} else {
"/$selectedUrl"
}
}
URL(baseUrl.protocol, baseUrl.host, baseUrl.port, path).toString()
}

// 解析子播放列表
return@withContext parse(fullUrl, client)
}

// 解析媒体播放列表
private fun parseMediaPlaylist(url: String, content: String): M3U8Info {
val lines = content.split("\n")
val segments = mutableListOf<M3U8Segment>()
var totalDuration = 0f
var segmentDuration = 0f
var segmentIndex = 0
var isFirstSegment = true

// 提取基础URL
val baseUrl = getBaseUrl(url)

for (line in lines) {
val trimmedLine = line.trim()

// 提取片段时长
if (trimmedLine.startsWith("#EXTINF:")) {
val durationText = trimmedLine.substring(8).split(",")[0]
segmentDuration = durationText.toFloat()
isFirstSegment = false
continue
}

// 提取片段URL
if (!trimmedLine.startsWith("#") && trimmedLine.isNotEmpty() && !isFirstSegment) {
// 构建完整URL
val segmentUrl = if (trimmedLine.startsWith("http")) {
trimmedLine
} else {
if (trimmedLine.startsWith("/")) {
// 绝对路径
val urlObj = URL(url)
URL(urlObj.protocol, urlObj.host, urlObj.port, trimmedLine).toString()
} else {
// 相对路径
"$baseUrl$trimmedLine"
}
}

segments.add(M3U8Segment(segmentUrl, segmentDuration, segmentIndex++))
totalDuration += segmentDuration
}
}

return M3U8Info(url, baseUrl, totalDuration, segments)
}

// 获取基础URL
private fun getBaseUrl(url: String): String {
val lastSlash = url.lastIndexOf('/')
return if (lastSlash != -1) {
url.substring(0, lastSlash + 1)
} else {
"$url/"
}
}
}

/**
* M3U8下载管理器
*/
class M3U8DownloadManager {
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()

private val downloadScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val m3u8Parser = M3U8Parser()
private val downloadManager = DownloadManager.getInstance()

// 下载状态
enum class M3U8DownloadStatus {
IDLE, PARSING, DOWNLOADING, MERGING, COMPLETED, FAILED, CANCELED
}

// M3U8下载监听器
interface M3U8DownloadListener {
fun onParsingProgress(url: String, progress: Int)
fun onDownloadProgress(url: String, progress: Int, downloadedSegments: Int, totalSegments: Int)
fun onMergingProgress(url: String, progress: Int)
fun onStatusChanged(url: String, status: M3U8DownloadStatus)
fun onSuccess(url: String, filePath: String)
fun onFailed(url: String, e: Exception)
}

// M3U8下载任务
data class M3U8DownloadTask(
val url: String,
val savePath: String,
val fileName: String,
var status: M3U8DownloadStatus = M3U8DownloadStatus.IDLE,
var m3u8Info: M3U8Parser.M3U8Info? = null,
var downloadedSegments: AtomicInteger = AtomicInteger(0),
var mergeProgress: AtomicInteger = AtomicInteger(0)
)

private val downloadTasks = ConcurrentHashMap<String, M3U8DownloadTask>()
private val listeners = ConcurrentHashMap<String, MutableList<M3U8DownloadListener>>()
private val activeDownloads = AtomicInteger(0)
private val maxConcurrentDownloads = 3

// 添加下载任务
fun addTask(url: String, savePath: String, fileName: String): M3U8DownloadTask {
val taskId = url.hashCode().toString()

return downloadTasks.getOrPut(taskId) {
// 创建保存目录
val saveDir = File(savePath)
if (!saveDir.exists()) {
saveDir.mkdirs()
}

// 创建临时目录
val tempDir = File(savePath, ".temp_$fileName")
if (!tempDir.exists()) {
tempDir.mkdirs()
}

M3U8DownloadTask(url, savePath, fileName)
}
}

// 添加监听器
fun addListener(url: String, listener: M3U8DownloadListener) {
val taskId = url.hashCode().toString()
val taskListeners = listeners.getOrPut(taskId) { mutableListOf() }
taskListeners.add(listener)
}

// 移除监听器
fun removeListener(url: String, listener: M3U8DownloadListener) {
val taskId = url.hashCode().toString()
listeners[taskId]?.remove(listener)
}

// 开始下载
fun startDownload(url: String) {
val taskId = url.hashCode().toString()
val task = downloadTasks[taskId] ?: return

if (task.status != M3U8DownloadStatus.IDLE &&
task.status != M3U8DownloadStatus.FAILED) {
return
}

// 修改状态为解析中
task.status = M3U8DownloadStatus.PARSING
notifyStatusChanged(task.url, task.status)

downloadScope.launch {
try {
// 1. 解析M3U8文件
notifyParsingProgress(task.url, 0)
val m3u8Info = m3u8Parser.parse(task.url, client)
task.m3u8Info = m3u8Info
notifyParsingProgress(task.url, 100)

// 2. 准备下载分片
task.status = M3U8DownloadStatus.DOWNLOADING
notifyStatusChanged(task.url, task.status)

// 重置计数器
task.downloadedSegments.set(0)

// 3. 下载所有分片
val tempDir = File(task.savePath, ".temp_${task.fileName}")
downloadAllSegments(task, m3u8Info, tempDir.absolutePath)

// 4. 合并分片
task.status = M3U8DownloadStatus.MERGING
notifyStatusChanged(task.url, task.status)
task.mergeProgress.set(0)

mergeSegments(task, m3u8Info, tempDir.absolutePath)

// 5. 完成
task.status = M3U8DownloadStatus.COMPLETED
notifyStatusChanged(task.url, task.status)

// 6. 清理临时文件
cleanupTempFiles(tempDir)

// 7. 通知成功
val outputFilePath = File(task.savePath, task.fileName).absolutePath
notifySuccess(task.url, outputFilePath)

} catch (e: Exception) {
if (task.status != M3U8DownloadStatus.CANCELED) {
task.status = M3U8DownloadStatus.FAILED
notifyStatusChanged(task.url, task.status)
notifyFailed(task.url, e)
}
}
}
}

// 下载所有分片
private suspend fun downloadAllSegments(
task: M3U8DownloadTask,
m3u8Info: M3U8Parser.M3U8Info,
tempDirPath: String
) = withContext(Dispatchers.IO) {
val totalSegments = m3u8Info.segmentList.size
val segmentJobs = mutableListOf<Deferred<Boolean>>()
val semaphore = Semaphore(20) // 限制同时下载的分片数

for (segment in m3u8Info.segmentList) {
val segmentFile = File(tempDirPath, "segment_${segment.index}.ts")
segment.tsFilePath = segmentFile.absolutePath

// 如果分片已存在且大小大于0,则跳过
if (segmentFile.exists() && segmentFile.length() > 0) {
task.downloadedSegments.incrementAndGet()
val progress = (task.downloadedSegments.get() * 100 / totalSegments)
notifyDownloadProgress(task.url, progress, task.downloadedSegments.get(), totalSegments)
continue
}

// 使用信号量限制并发
semaphore.acquire()

val job = downloadScope.async {
try {
// 下载分片
val request = Request.Builder()
.url(segment.url)
.build()

client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw IOException("Failed to download segment: ${response.code}")
}

val responseBody = response.body ?: throw IOException("Empty response body")

// 保存分片
segmentFile.sink().buffer().use { sink ->
responseBody.source().use { source ->
sink.writeAll(source)
}
}

// 更新进度
val downloaded = task.downloadedSegments.incrementAndGet()
val progress = (downloaded * 100 / totalSegments)
notifyDownloadProgress(task.url, progress, downloaded, totalSegments)

return@async true
}
} catch (e: Exception) {
return@async false
} finally {
semaphore.release()
}
}

segmentJobs.add(job)
}

// 等待所有分片下载完成
val results = segmentJobs.awaitAll()

// 检查是否有失败的分片
if (results.contains(false)) {
throw IOException("Some segments failed to download")
}
}

// 合并分片
private suspend fun mergeSegments(
task: M3U8DownloadTask,
m3u8Info: M3U8Parser.M3U8Info,
tempDirPath: String
) = withContext(Dispatchers.IO) {
val segments = m3u8Info.segmentList
val totalSegments = segments.size
val outputFile = File(task.savePath, task.fileName)

// 如果是mp4文件,需要先合并为ts,再转换为mp4
val isMp4 = task.fileName.endsWith(".mp4", ignoreCase = true)
val tempOutputFile = if (isMp4) {
File(task.savePath, "${task.fileName}.ts")
} else {
outputFile
}

// 创建输出流
val outputStream = FileOutputStream(tempOutputFile)

try {
// 依次写入每个分片
for ((index, segment) in segments.withIndex()) {
val segmentFile = File(segment.tsFilePath)
if (!segmentFile.exists()) {
throw IOException("Segment file not found: ${segment.tsFilePath}")
}

// 写入分片数据
segmentFile.source().buffer().use { source ->
outputStream.sink().buffer().use { sink ->
sink.writeAll(source)
}
}

// 更新进度
val progress = ((index + 1) * 100 / totalSegments)
task.mergeProgress.set(progress)
notifyMergingProgress(task.url, progress)
}
} finally {
outputStream.close()
}

// 如果是mp4,需要进行格式转换
if (isMp4) {
// 这里使用简单文件重命名代替格式转换
// 实际应用中,应该使用FFmpeg等工具进行正确的格式转换
if (tempOutputFile.exists()) {
tempOutputFile.renameTo(outputFile)
}
}
}

// 清理临时文件
private fun cleanupTempFiles(tempDir: File) {
if (tempDir.exists()) {
tempDir.listFiles()?.forEach { it.delete() }
tempDir.delete()
}
}

// 取消下载
fun cancelDownload(url: String) {
val taskId = url.hashCode().toString()
val task = downloadTasks[taskId] ?: return

task.status = M3U8DownloadStatus.CANCELED
notifyStatusChanged(task.url, task.status)

// 清理临时目录
val tempDir = File(task.savePath, ".temp_${task.fileName}")
cleanupTempFiles(tempDir)
}

// 获取下载任务
fun getTask(url: String): M3U8DownloadTask? {
val taskId = url.hashCode().toString()
return downloadTasks[taskId]
}

// 通知解析进度
private fun notifyParsingProgress(url: String, progress: Int) {
val taskId = url.hashCode().toString()
listeners[taskId]?.forEach { listener ->
listener.onParsingProgress(url, progress)
}
}

// 通知下载进度
private fun notifyDownloadProgress(url: String, progress: Int, downloadedSegments: Int, totalSegments: Int) {
val taskId = url.hashCode().toString()
listeners[taskId]?.forEach { listener ->
listener.onDownloadProgress(url, progress, downloadedSegments, totalSegments)
}
}

// 通知合并进度
private fun notifyMergingProgress(url: String, progress: Int) {
val taskId = url.hashCode().toString()
listeners[taskId]?.forEach { listener ->
listener.onMergingProgress(url, progress)
}
}

// 通知状态变化
private fun notifyStatusChanged(url: String, status: M3U8DownloadStatus) {
val taskId = url.hashCode().toString()
listeners[taskId]?.forEach { listener ->
listener.onStatusChanged(url, status)
}
}

// 通知下载成功
private fun notifySuccess(url: String, filePath: String) {
val taskId = url.hashCode().toString()
listeners[taskId]?.forEach { listener ->
listener.onSuccess(url, filePath)
}
}

// 通知下载失败
private fun notifyFailed(url: String, e: Exception) {
val taskId = url.hashCode().toString()
listeners[taskId]?.forEach { listener ->
listener.onFailed(url, e)
}
}

// 释放资源
fun release() {
downloadScope.cancel()
downloadTasks.clear()
listeners.clear()
}
}

使用示例

以下是如何使用M3U8下载功能的示例代码:

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
// M3U8下载示例

fun main() {
// 创建M3U8下载管理器
val m3u8DownloadManager = M3U8DownloadManager()

// 添加下载任务
val task = m3u8DownloadManager.addTask(
url = "https://example.com/video.m3u8",
savePath = "/downloads",
fileName = "video.mp4" // 可以是.mp4或.ts格式
)

// 添加下载监听器
m3u8DownloadManager.addListener(task.url, object : M3U8DownloadManager.M3U8DownloadListener {
override fun onParsingProgress(url: String, progress: Int) {
println("解析进度: $progress%")
}

override fun onDownloadProgress(url: String, progress: Int, downloadedSegments: Int, totalSegments: Int) {
println("下载进度: $progress%, 已下载分片: $downloadedSegments/$totalSegments")
}

override fun onMergingProgress(url: String, progress: Int) {
println("合并进度: $progress%")
}

override fun onStatusChanged(url: String, status: M3U8DownloadManager.M3U8DownloadStatus) {
println("状态变更: $status")
}

override fun onSuccess(url: String, filePath: String) {
println("下载成功: $filePath")
}

override fun onFailed(url: String, e: Exception) {
println("下载失败: ${e.message}")
}
})

// 开始下载
m3u8DownloadManager.startDownload(task.url)

// 等待下载完成
readLine()

// 清理资源
m3u8DownloadManager.release()
}

M3U8下载功能说明

  1. M3U8文件解析

    • 支持解析主播放列表和媒体播放列表
    • 自动选择最高质量的流进行下载
    • 处理相对路径和绝对路径的URL
  2. 分片下载

    • 支持高并发分片下载
    • 使用信号量控制并发数量
    • 支持已下载分片检测,避免重复下载
  3. 下载进度

    • 提供三个阶段的进度回调:解析进度、下载进度、合并进度
    • 详细的状态变化通知
  4. 文件合并

    • 按顺序合并所有TS分片
    • 支持MP4格式输出(需配合实际工具进行格式转换)
    • 自动清理临时文件
  5. 异常处理

    • 完善的错误处理机制
    • 支持取消下载操作
    • 出错时自动清理临时文件

注意事项

  1. 关于格式转换
    本示例中的MP4格式转换仅做演示,实际应用中应该使用专业工具(如FFmpeg)进行正确的格式转换。

  2. 有关DRM保护
    一些M3U8流可能有DRM保护,需要额外的解密逻辑。您可以扩展此框架添加解密功能。

  3. 性能优化

    • 调整Semaphore的许可数量来控制并发下载量
    • 可以根据网络状况动态调整并发数
    • 对于大型视频,考虑增加磁盘缓冲区大小

希望这个M3U8下载框架能满足您的需求!您可以根据实际项目需要进一步扩展其功能。

作者

Dench

发布于

2025-04-12

更新于

2025-04-12

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×