-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathVideoWriter.swift
178 lines (140 loc) · 5.86 KB
/
VideoWriter.swift
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
//
// VideoWriter.swift
// Drone
//
// Created by Ramsundar Shandilya on 1/10/18.
// Copyright © 2018 Ramsundar Shandilya. All rights reserved.
//
import Foundation
import AVFoundation
import AVKit
class VideoWriter {
private static let videoCacheFileName = "VideoCache.h264"
var isWriting = false
var outputURL: URL
private var videoDecoder = VideoDecoder()
private var frameCount = 0
private var assetWriter: AVAssetWriter?
private var videoWriterInput: AVAssetWriterInput?
private var avAdaptor: AVAssetWriterInputPixelBufferAdaptor?
private var elementaryStreamData: Data?
init(url: URL) {
outputURL = url
}
func prepareToWrite() {
videoDecoder.delegate = self
elementaryStreamData = Data()
}
func write(videoData: Data) {
if !isWriting {
isWriting = true
}
elementaryStreamData?.append(videoData)
}
func finishWriting(completion: @escaping () -> Void) {
isWriting = false
guard let cacheURL = saveElementaryStreamData() else {
return
}
saveVideoToMp4(source: cacheURL, completion: completion)
}
private func saveElementaryStreamData() -> URL? {
guard let documentDirectory = AssetFileManager.documentDirectory() else { return nil }
do {
let fileURL = documentDirectory.fileURL().appendingPathComponent(VideoWriter.videoCacheFileName)
let fileManager = AssetFileManager.fileManager()
if fileManager.fileExists(atPath: fileURL.path) {
try fileManager.removeItem(atPath: fileURL.path)
}
try elementaryStreamData?.write(to: fileURL)
return fileURL
} catch {
Log.print("No such directory")
}
return nil
}
private func saveVideoToMp4(source: URL, completion: @escaping () -> Void) {
setupAssetWriter()
parse(fileURL: source, completion: completion)
videoWriterInput?.markAsFinished()
assetWriter?.finishWriting {
let path = self.assetWriter?.outputURL.path ?? ""
print("Finshed writing file at \(path)")
completion()
}
}
private func setupAssetWriter() {
let fileManager = AssetFileManager.fileManager()
if fileManager.fileExists(atPath: outputURL.path) {
do {
try fileManager.removeItem(atPath: outputURL.path)
} catch {
Log.print("Error deleting existing file: \(error)")
}
}
assetWriter = try? AVAssetWriter(url: outputURL, fileType: AVFileType.mp4)
let outputSettings: [String : Any] = [AVVideoCodecKey : AVVideoCodecType.h264, AVVideoWidthKey : NSNumber(value: 640), AVVideoHeightKey : NSNumber(value: 480)]
guard let canApply = assetWriter?.canApply(outputSettings: outputSettings, forMediaType: AVMediaType.video), canApply else {
fatalError("Negative : Can't apply the Output settings...")
}
videoWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: outputSettings)
videoWriterInput?.expectsMediaDataInRealTime = true
if let videoWriterInput = videoWriterInput,
let canAdd = assetWriter?.canAdd(videoWriterInput),
canAdd {
avAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriterInput, sourcePixelBufferAttributes: nil)
assetWriter?.add(videoWriterInput)
}
assetWriter?.startWriting()
assetWriter?.startSession(atSourceTime: kCMTimeZero)
}
func parse(fileURL: URL, completion: @escaping () -> Void) {
guard let fileStream = InputStream(fileAtPath: fileURL.path) else {
return
}
fileStream.open()
let bufferCap = 921600 //720 * 1280
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferCap)
while fileStream.hasBytesAvailable {
let read = fileStream.read(buffer, maxLength: bufferCap)
guard read > 4 else {
break
}
var startCodeIndices: [Int] = []
for i in 0 ..< read-4 {
if buffer[i] == UInt8(0) &&
buffer[i+1] == UInt8(0) &&
buffer[i+2] == UInt8(0) &&
buffer[i+3] == UInt8(1) {
startCodeIndices.append(i)
}
}
for i in 0 ..< startCodeIndices.count - 1 {
let startCodeIndex = startCodeIndices[i]
let nextStartCodeIndex = startCodeIndices[i+1]
let distance = nextStartCodeIndex - startCodeIndex
let nalu = UnsafeMutablePointer<UInt8>.allocate(capacity: distance)
nalu.initialize(from: buffer.advanced(by: startCodeIndex), count: distance)
let naluData = NSData(bytesNoCopy: nalu, length: distance, freeWhenDone: false)
videoDecoder.parseNALU(nalu: naluData)
}
}
}
}
extension VideoWriter: VideoDecoderDelegate {
func videoDecoderDidDecode(buffer: CVImageBuffer) {
var didAppendBuffer = false
while !didAppendBuffer {
if videoWriterInput!.isReadyForMoreMediaData {
avAdaptor?.append(buffer, withPresentationTime: CMTimeMake(Int64(frameCount * 10), 300))
frameCount += 1
didAppendBuffer = true
} else {
Thread.sleep(forTimeInterval: 0.1)
}
}
}
func videoDecoderDidFailToDecode(error: VideoDecoderError) {
print(error.description)
}
}