-
Notifications
You must be signed in to change notification settings - Fork 7
/
ViewController.swift
233 lines (171 loc) · 9.06 KB
/
ViewController.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
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
//
// ViewController.swift
// SwiftH264
//
// Created by zhongzhendong on 4/20/16.
// Copyright © 2016 zhongzhendong. All rights reserved.
//
import UIKit
import VideoToolbox
import AVFoundation
class ViewController: UIViewController {
var formatDesc: CMVideoFormatDescription?
var decompressionSession: VTDecompressionSession?
var videoLayer: AVSampleBufferDisplayLayer?
var spsSize: Int = 0
var ppsSize: Int = 0
var sps: Array<UInt8>?
var pps: Array<UInt8>?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
videoLayer = AVSampleBufferDisplayLayer()
if let layer = videoLayer {
layer.frame = CGRect(x: 0, y: 400, width: 300, height: 300)
layer.videoGravity = AVLayerVideoGravityResizeAspect
let _CMTimebasePointer = UnsafeMutablePointer<CMTimebase?>.allocate(capacity: 1)
let status = CMTimebaseCreateWithMasterClock( kCFAllocatorDefault, CMClockGetHostTimeClock(), _CMTimebasePointer )
layer.controlTimebase = _CMTimebasePointer.pointee
if let controlTimeBase = layer.controlTimebase, status == noErr {
CMTimebaseSetTime(controlTimeBase, kCMTimeZero);
CMTimebaseSetRate(controlTimeBase, 1.0);
}
self.view.layer.addSublayer(layer)
}
}
@IBAction func startClicked(_ sender: UIButton) {
DispatchQueue.global().async {
let filePath = Bundle.main.path(forResource: "mtv", ofType: "h264")
let url = URL(fileURLWithPath: filePath!)
self.decodeFile(url)
}
}
func decodeFile(_ fileURL: URL) {
let videoReader = VideoFileReader()
videoReader.openVideoFile(fileURL)
while var packet = videoReader.netPacket() {
self.receivedRawVideoFrame(&packet)
}
}
func receivedRawVideoFrame(_ videoPacket: inout VideoPacket) {
//replace start code with nal size
var biglen = CFSwapInt32HostToBig(UInt32(videoPacket.count - 4))
memcpy(&videoPacket, &biglen, 4)
let nalType = videoPacket[4] & 0x1F
switch nalType {
case 0x05:
print("Nal type is IDR frame")
if createDecompSession() {
decodeVideoPacket(videoPacket)
}
case 0x07:
print("Nal type is SPS")
spsSize = videoPacket.count - 4
sps = Array(videoPacket[4..<videoPacket.count])
case 0x08:
print("Nal type is PPS")
ppsSize = videoPacket.count - 4
pps = Array(videoPacket[4..<videoPacket.count])
default:
print("Nal type is B/P frame")
decodeVideoPacket(videoPacket)
break;
}
print("Read Nalu size \(videoPacket.count)");
}
func decodeVideoPacket(_ videoPacket: VideoPacket) {
let bufferPointer = UnsafeMutablePointer<UInt8>(mutating: videoPacket)
var blockBuffer: CMBlockBuffer?
var status = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault,bufferPointer, videoPacket.count,
kCFAllocatorNull,
nil, 0, videoPacket.count,
0, &blockBuffer)
if status != kCMBlockBufferNoErr {
return
}
var sampleBuffer: CMSampleBuffer?
let sampleSizeArray = [videoPacket.count]
status = CMSampleBufferCreateReady(kCFAllocatorDefault,
blockBuffer,
formatDesc,
1, 0, nil,
1, sampleSizeArray,
&sampleBuffer)
if let buffer = sampleBuffer, let session = decompressionSession, status == kCMBlockBufferNoErr {
let attachments:CFArray? = CMSampleBufferGetSampleAttachmentsArray(buffer, true)
if let attachmentArray = attachments {
let dic = unsafeBitCast(CFArrayGetValueAtIndex(attachmentArray, 0), to: CFMutableDictionary.self)
CFDictionarySetValue(dic,
Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(),
Unmanaged.passUnretained(kCFBooleanTrue).toOpaque())
}
//diaplay with AVSampleBufferDisplayLayer
self.videoLayer?.enqueue(buffer)
DispatchQueue.main.async(execute: {
self.videoLayer?.setNeedsDisplay()
})
// or decompression to CVPixcelBuffer
var flagOut = VTDecodeInfoFlags(rawValue: 0)
var outputBuffer = UnsafeMutablePointer<CVPixelBuffer>.allocate(capacity: 1)
status = VTDecompressionSessionDecodeFrame(session, buffer,
[._EnableAsynchronousDecompression],
&outputBuffer, &flagOut)
if status == noErr {
print("OK")
}else if(status == kVTInvalidSessionErr) {
print("IOS8VT: Invalid session, reset decoder session");
} else if(status == kVTVideoDecoderBadDataErr) {
print("IOS8VT: decode failed status=\(status)(Bad data)");
} else if(status != noErr) {
print("IOS8VT: decode failed status=\(status)");
}
}
}
func createDecompSession() -> Bool{
formatDesc = nil
if let spsData = sps, let ppsData = pps {
let pointerSPS = UnsafePointer<UInt8>(spsData)
let pointerPPS = UnsafePointer<UInt8>(ppsData)
// make pointers array
let dataParamArray = [pointerSPS, pointerPPS]
let parameterSetPointers = UnsafePointer<UnsafePointer<UInt8>>(dataParamArray)
// make parameter sizes array
let sizeParamArray = [spsData.count, ppsData.count]
let parameterSetSizes = UnsafePointer<Int>(sizeParamArray)
let status = CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault, 2, parameterSetPointers, parameterSetSizes, 4, &formatDesc)
if let desc = formatDesc, status == noErr {
if let session = decompressionSession {
VTDecompressionSessionInvalidate(session)
decompressionSession = nil
}
var videoSessionM : VTDecompressionSession?
let decoderParameters = NSMutableDictionary()
let destinationPixelBufferAttributes = NSMutableDictionary()
destinationPixelBufferAttributes.setValue(NSNumber(value: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange as UInt32), forKey: kCVPixelBufferPixelFormatTypeKey as String)
var outputCallback = VTDecompressionOutputCallbackRecord()
outputCallback.decompressionOutputCallback = decompressionSessionDecodeFrameCallback
outputCallback.decompressionOutputRefCon = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
let status = VTDecompressionSessionCreate(kCFAllocatorDefault,
desc, decoderParameters,
destinationPixelBufferAttributes,&outputCallback,
&videoSessionM)
if(status != noErr) {
print("\t\t VTD ERROR type: \(status)")
}
self.decompressionSession = videoSessionM
}else {
print("IOS8VT: reset decoder session failed status=\(status)")
}
}
return true
}
func displayDecodedFrame(_ imageBuffer: CVImageBuffer?) {
}
}
private func decompressionSessionDecodeFrameCallback(_ decompressionOutputRefCon: UnsafeMutableRawPointer?, _ sourceFrameRefCon: UnsafeMutableRawPointer?, _ status: OSStatus, _ infoFlags: VTDecodeInfoFlags, _ imageBuffer: CVImageBuffer?, _ presentationTimeStamp: CMTime, _ presentationDuration: CMTime) -> Void {
let streamManager: ViewController = unsafeBitCast(decompressionOutputRefCon, to: ViewController.self)
if status == noErr {
// do something with your resulting CVImageBufferRef that is your decompressed frame
streamManager.displayDecodedFrame(imageBuffer);
}
}