Skip to content

Instantly share code, notes, and snippets.

@tetkuz
Created October 4, 2017 02:49
Show Gist options
  • Save tetkuz/04fa1ae1c8f4e9a5d1920cd59057ea3c to your computer and use it in GitHub Desktop.
Save tetkuz/04fa1ae1c8f4e9a5d1920cd59057ea3c to your computer and use it in GitHub Desktop.
Dump H.264 data of a movie file using AVAssetReader
func dumpH264(_ path:URL) -> Void {
let asset:AVURLAsset = AVURLAsset(url:path, options:nil)
let video_tracks:Array = asset.tracks(withMediaType: AVMediaTypeVideo)
var output:AVAssetReaderOutput? = nil
do {
try self.asset_reader = AVAssetReader.init(asset: asset)
} catch {
fatalError("Unable to read Asset: \(error)")
}
if let video_track = video_tracks.first {
output = AVAssetReaderTrackOutput(track: video_track, outputSettings: nil)
self.asset_reader!.add(output!)
self.asset_reader!.startReading()
}
while (self.asset_reader!.status == AVAssetReaderStatus.reading) {
if let sampleBuffer = output!.copyNextSampleBuffer() {
if let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer){
let length = CMBlockBufferGetDataLength(blockBuffer)
let tempBytes = UnsafeMutableRawPointer.allocate(bytes: length, alignedTo: 1)
var returnedPointer: UnsafeMutablePointer<Int8>?
if CMBlockBufferAccessDataBytes(blockBuffer, 0, length, tempBytes, &returnedPointer) != kCMBlockBufferNoErr {
break
} else {
tempBytes.deallocate(bytes: length, alignedTo: 1)
let data = Data(bytes: returnedPointer!, count: length)
var byteArray = [UInt8](repeating: 0x0, count: length)
data.copyBytes(to: &byteArray, count:length)
for v in byteArray {
print(String(format: "0x%02x", v))
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment