This repository was archived by the owner on Jul 8, 2024. It is now read-only.
forked from HaishinKit/HaishinKit.swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTSWriter.swift
More file actions
478 lines (421 loc) · 16.5 KB
/
Copy pathTSWriter.swift
File metadata and controls
478 lines (421 loc) · 16.5 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
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
import AVFoundation
import CoreMedia
import Foundation
#if canImport(SwiftPMSupport)
import SwiftPMSupport
#endif
/// The interface an MPEG-2 TS (Transport Stream) writer uses to inform its delegates.
public protocol TSWriterDelegate: AnyObject {
func writer(_ writer: TSWriter, didRotateFileHandle timestamp: CMTime)
func writer(_ writer: TSWriter, didOutput data: Data)
func didGenerateTS(_ file: URL)
func didGenerateM3U8(_ file: URL)
}
public extension TSWriterDelegate {
// default implementation noop
func writer(_ writer: TSWriter, didRotateFileHandle timestamp: CMTime) {
// noop
}
}
/// The TSWriter class represents writes MPEG-2 transport stream data.
public class TSWriter: Running {
public static let defaultPATPID: UInt16 = 0
public static let defaultPMTPID: UInt16 = 4095
public static let defaultVideoPID: UInt16 = 256
public static let defaultAudioPID: UInt16 = 257
public static let defaultSegmentDuration: Double = 2
/// The delegate instance.
public weak var delegate: (any TSWriterDelegate)?
/// This instance is running to process(true) or not(false).
public internal(set) var isRunning: Atomic<Bool> = .init(false)
/// The exptected medias = [.video, .audio].
public var expectedMedias: Set<AVMediaType> = [] {
didSet {
print("expected medias \(expectedMedias.count)")
}
}
var audioContinuityCounter: UInt8 = 0
var videoContinuityCounter: UInt8 = 0
var PCRPID: UInt16 = TSWriter.defaultVideoPID
var rotatedTimestamp = CMTime.zero
var segmentDuration: Double = TSWriter.defaultSegmentDuration
let lockQueue = DispatchQueue(label: "com.haishinkit.HaishinKit.TSWriter.lock")
private(set) var PAT: TSProgramAssociation = {
let PAT: TSProgramAssociation = .init()
PAT.programs = [1: TSWriter.defaultPMTPID]
return PAT
}()
private(set) var PMT: TSProgramMap = .init()
private var audioConfig: AudioSpecificConfig? {
didSet {
writeProgramIfNeeded()
}
}
private var videoConfig: AVCDecoderConfigurationRecord? {
didSet {
writeProgramIfNeeded()
}
}
private var videoTimestamp: CMTime = .invalid
private var audioTimestamp: CMTime = .invalid
private var PCRTimestamp = CMTime.zero
private var canWriteFor: Bool {
guard expectedMedias.isEmpty else {
return true
}
if expectedMedias.contains(.audio) && expectedMedias.contains(.video) {
return audioConfig != nil && videoConfig != nil
}
if expectedMedias.contains(.video) {
return videoConfig != nil
}
if expectedMedias.contains(.audio) {
return audioConfig != nil
}
return false
}
public init(segmentDuration: Double = TSWriter.defaultSegmentDuration) {
self.segmentDuration = segmentDuration
}
public func startRunning() {
guard isRunning.value else {
return
}
isRunning.mutate { $0 = true }
}
public func stopRunning() {
guard !isRunning.value else {
return
}
audioContinuityCounter = 0
videoContinuityCounter = 0
PCRPID = TSWriter.defaultVideoPID
PAT.programs.removeAll()
PAT.programs = [1: TSWriter.defaultPMTPID]
PMT = TSProgramMap()
audioConfig = nil
videoConfig = nil
videoTimestamp = .invalid
audioTimestamp = .invalid
PCRTimestamp = .invalid
isRunning.mutate { $0 = false }
}
// swiftlint:disable:next function_parameter_count
final func writeSampleBuffer(_ PID: UInt16, streamID: UInt8, bytes: UnsafePointer<UInt8>?, count: UInt32, presentationTimeStamp: CMTime, decodeTimeStamp: CMTime, randomAccessIndicator: Bool) {
guard canWriteFor else {
return
}
switch PID {
case TSWriter.defaultAudioPID:
guard audioTimestamp == .invalid else { break }
audioTimestamp = presentationTimeStamp
if PCRPID == PID {
PCRTimestamp = presentationTimeStamp
}
case TSWriter.defaultVideoPID:
guard videoTimestamp == .invalid else { break }
videoTimestamp = presentationTimeStamp
if PCRPID == PID {
PCRTimestamp = presentationTimeStamp
}
default:
break
}
guard var PES = PacketizedElementaryStream.create(
bytes,
count: count,
presentationTimeStamp: presentationTimeStamp,
decodeTimeStamp: decodeTimeStamp,
timestamp: PID == TSWriter.defaultVideoPID ? videoTimestamp : audioTimestamp,
config: streamID == 192 ? audioConfig : videoConfig,
randomAccessIndicator: randomAccessIndicator) else {
return
}
PES.streamID = streamID
let timestamp = decodeTimeStamp == .invalid ? presentationTimeStamp : decodeTimeStamp
let packets: [TSPacket] = split(PID, PES: PES, timestamp: timestamp)
rotateFileHandle(timestamp)
packets[0].adaptationField?.randomAccessIndicator = randomAccessIndicator
var bytes = Data()
for var packet in packets {
switch PID {
case TSWriter.defaultAudioPID:
packet.continuityCounter = audioContinuityCounter
audioContinuityCounter = (audioContinuityCounter + 1) & 0x0f
case TSWriter.defaultVideoPID:
packet.continuityCounter = videoContinuityCounter
videoContinuityCounter = (videoContinuityCounter + 1) & 0x0f
default:
break
}
bytes.append(packet.data)
}
write(bytes)
}
func rotateFileHandle(_ timestamp: CMTime) {
let duration: Double = timestamp.seconds - rotatedTimestamp.seconds
if duration <= segmentDuration {
return
}
writeProgram()
rotatedTimestamp = timestamp
delegate?.writer(self, didRotateFileHandle: timestamp)
}
func write(_ data: Data) {
delegate?.writer(self, didOutput: data)
}
final func writeProgram() {
PMT.PCRPID = PCRPID
var bytes = Data()
var packets: [TSPacket] = []
packets.append(contentsOf: PAT.arrayOfPackets(TSWriter.defaultPATPID))
packets.append(contentsOf: PMT.arrayOfPackets(TSWriter.defaultPMTPID))
for packet in packets {
bytes.append(packet.data)
}
write(bytes)
}
final func writeProgramIfNeeded() {
guard !expectedMedias.isEmpty else {
return
}
guard canWriteFor else {
return
}
writeProgram()
}
private func split(_ PID: UInt16, PES: PacketizedElementaryStream, timestamp: CMTime) -> [TSPacket] {
var PCR: UInt64?
let duration: Double = timestamp.seconds - PCRTimestamp.seconds
if PCRPID == PID && 0.02 <= duration {
PCR = UInt64((timestamp.seconds - (PID == TSWriter.defaultVideoPID ? videoTimestamp : audioTimestamp).seconds) * TSTimestamp.resolution)
PCRTimestamp = timestamp
}
var packets: [TSPacket] = []
for packet in PES.arrayOfPackets(PID, PCR: PCR) {
packets.append(packet)
}
return packets
}
}
extension TSWriter: AudioCodecDelegate {
// MARK: AudioCodecDelegate
public func audioCodec(_ codec: AudioCodec, errorOccurred error: AudioCodec.Error) {
}
public func audioCodec(_ codec: AudioCodec, didOutput outputFormat: AVAudioFormat) {
var data = ESSpecificData()
data.streamType = .adtsAac
data.elementaryPID = TSWriter.defaultAudioPID
PMT.elementaryStreamSpecificData.append(data)
audioContinuityCounter = 0
audioConfig = AudioSpecificConfig(formatDescription: outputFormat.formatDescription)
}
public func audioCodec(_ codec: AudioCodec, didOutput audioBuffer: AVAudioBuffer, when: AVAudioTime) {
guard let audioBuffer = audioBuffer as? AVAudioCompressedBuffer else {
return
}
writeSampleBuffer(
TSWriter.defaultAudioPID,
streamID: 192,
bytes: audioBuffer.data.assumingMemoryBound(to: UInt8.self),
count: audioBuffer.byteLength,
presentationTimeStamp: when.makeTime(),
decodeTimeStamp: .invalid,
randomAccessIndicator: true
)
codec.releaseOutputBuffer(audioBuffer)
}
}
extension TSWriter: VideoCodecDelegate {
// MARK: VideoCodecDelegate
public func videoCodec(_ codec: VideoCodec, didOutput formatDescription: CMFormatDescription?) {
guard
let formatDescription,
let avcC = AVCDecoderConfigurationRecord.getData(formatDescription) else {
return
}
var data = ESSpecificData()
data.streamType = .h264
data.elementaryPID = TSWriter.defaultVideoPID
PMT.elementaryStreamSpecificData.append(data)
videoContinuityCounter = 0
videoConfig = AVCDecoderConfigurationRecord(data: avcC)
}
public func videoCodec(_ codec: VideoCodec, didOutput sampleBuffer: CMSampleBuffer) {
guard let dataBuffer = sampleBuffer.dataBuffer else {
return
}
var length = 0
var buffer: UnsafeMutablePointer<Int8>?
guard CMBlockBufferGetDataPointer(dataBuffer, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &length, dataPointerOut: &buffer) == noErr else {
return
}
guard let bytes = buffer else {
return
}
writeSampleBuffer(
TSWriter.defaultVideoPID,
streamID: 224,
bytes: UnsafeRawPointer(bytes).bindMemory(to: UInt8.self, capacity: length),
count: UInt32(length),
presentationTimeStamp: sampleBuffer.presentationTimeStamp,
decodeTimeStamp: sampleBuffer.decodeTimeStamp,
randomAccessIndicator: !sampleBuffer.isNotSync
)
}
public func videoCodec(_ codec: VideoCodec, errorOccurred error: VideoCodec.Error) {
}
}
public class TSFileWriter: TSWriter {
static let defaultSegmentCount: Int = 10000
static let defaultSegmentMaxCount: Int = 10000
public var baseFolder: URL?
public var shouldAppendToStream: Bool = false
var segmentMaxCount: Int = TSFileWriter.defaultSegmentMaxCount
private(set) var files: [M3UMediaInfo] = []
private var currentFileHandle: FileHandle?
private var currentFileURL: URL?
private var sequence: Int = 0
public var isDiscontinuity = false
private var isTerminating: Bool = false
var playlist: String {
var m3u8 = M3U()
m3u8.targetDuration = segmentDuration
if sequence <= TSFileWriter.defaultSegmentMaxCount {
m3u8.mediaSequence = 0
m3u8.mediaList = files
for mediaItem in m3u8.mediaList where mediaItem.duration > m3u8.targetDuration {
m3u8.targetDuration = mediaItem.duration + 1
}
return m3u8.description
}
let startIndex = max(0, files.count - TSFileWriter.defaultSegmentCount)
m3u8.mediaSequence = sequence - TSFileWriter.defaultSegmentMaxCount
m3u8.mediaList = Array(files[startIndex..<files.count])
for mediaItem in m3u8.mediaList where mediaItem.duration > m3u8.targetDuration {
m3u8.targetDuration = mediaItem.duration + 1
}
return m3u8.description
}
override func rotateFileHandle(_ timestamp: CMTime) {
let duration: Double = timestamp.seconds - rotatedTimestamp.seconds
if duration <= segmentDuration {
return
}
let fileManager = FileManager.default
guard let base = baseFolder else {
return
}
#if os(OSX)
let bundleIdentifier: String? = Bundle.main.bundleIdentifier
let temp: String = bundleIdentifier == nil ? NSTemporaryDirectory() : NSTemporaryDirectory() + bundleIdentifier! + "/"
#else
let temp: String = NSTemporaryDirectory()
#endif
if !fileManager.fileExists(atPath: temp) {
do {
try fileManager.createDirectory(atPath: temp, withIntermediateDirectories: false, attributes: nil)
} catch {
logger.warn(error)
}
}
// let filename: String = Int(timestamp.seconds).description + ".ts"
let playlistUrl = base.appendingPathComponent("ScreenRecording.m3u8")
let filename = String(format: "part%.5i.ts", sequence)
let url = base.appendingPathComponent(filename)
if isTerminating { return }
// Toss part0 due to bad duration calculation.
// shouldAppendToStream is true when countdown-completed arrives
if let currentUrl = currentFileURL, sequence > 1 && shouldAppendToStream {
// let asset = AVAsset(url: currentUrl)
// let calculatedDuration = CMTimeGetSeconds(asset.duration)
// Logger.info("Duration: \(duration) Calculated duration: \(calculatedDuration)")
files.append(M3UMediaInfo(url: currentUrl, duration: duration, isDiscontinuous: isDiscontinuity))
isDiscontinuity = false
fileManager.createFile(atPath: playlistUrl.path, contents: playlist.data(using: .utf8), attributes: nil)
notifyDelegate(tsUrl: currentUrl, playlistUrl: playlistUrl)
}
sequence += 1
if shouldAppendToStream {
segmentDuration = 2
} else {
segmentDuration = 1
}
fileManager.createFile(atPath: url.path, contents: nil, attributes: nil)
if TSFileWriter.defaultSegmentMaxCount <= files.count {
let info: M3UMediaInfo = files.removeFirst()
do {
try fileManager.removeItem(at: info.url as URL)
} catch {
logger.warn(error)
}
}
currentFileURL = url
audioContinuityCounter = 0
videoContinuityCounter = 0
nstry({
self.currentFileHandle?.synchronizeFile()
}, { exeption in
logger.warn("\(exeption)")
})
currentFileHandle?.closeFile()
currentFileHandle = try? FileHandle(forWritingTo: url)
writeProgram()
rotatedTimestamp = timestamp
}
func notifyDelegate(tsUrl: URL, playlistUrl: URL) {
self.delegate?.didGenerateTS(tsUrl)
self.delegate?.didGenerateM3U8(playlistUrl)
}
private func writeFinal() {
guard let base = baseFolder else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now()+(TSWriter.defaultSegmentDuration+1)) {
if let currentUrl = self.currentFileURL {
let playlistUrl = base.appendingPathComponent("ScreenRecording.m3u8")
self.files.append(M3UMediaInfo(url: currentUrl, duration: TSWriter.defaultSegmentDuration, isDiscontinuous: false))
FileManager.default.createFile(atPath: playlistUrl.path, contents: self.playlist.data(using: .utf8), attributes: nil)
self.notifyDelegate(tsUrl: currentUrl, playlistUrl: playlistUrl)
}
self.currentFileURL = nil
self.currentFileHandle = nil
super.stopRunning()
}
}
override func write(_ data: Data) {
nstry({
self.currentFileHandle?.write(data)
}, { exception in
self.currentFileHandle?.write(data)
logger.warn("\(exception)")
})
super.write(data)
}
public override func stopRunning() {
guard !isRunning.value else {
return
}
nstry({
self.currentFileHandle?.synchronizeFile()
}, { exeption in
// Logger.warn("\(exeption)")
})
currentFileHandle?.closeFile()
writeFinal()
}
func getFilePath(_ fileName: String) -> String? {
files.first { $0.url.absoluteString.contains(fileName) }?.url.path
}
private func removeFiles() {
let fileManager = FileManager.default
for info in files {
do {
try fileManager.removeItem(at: info.url as URL)
} catch {
logger.warn(error)
}
}
files.removeAll()
}
}