Search code examples
swift3avfoundationavassetavassetreadertimecodes

How to read a timecode track with AVAsset and Swift 3?


I'd like to read the time value of a timecode track. There is an excellent documentation from Apple (see Technical Note 2310) but it's written in Objective C.

I have translated the core logic to Swift 3. It works exactly as the ObjC version, which means that a CMSampleBuffer from a timecode track is read and converted to a CMBlockBuffer. It fails when I create the data pointer CMBlockBufferGetDataPointer (in the timecodeFrame() func), which means, that the raw data is always giving me 0 frames. So it boils down to the question, how do I handle the raw data correctly?

import Foundation
import AVFoundation
import CoreMedia

let movie = URL(fileURLWithPath: "videoWithTimecodeTrack.mov")
let asset = AVAsset(url: movie)

asset.loadValuesAsynchronously(forKeys: ["tracks"]) {

    var error: NSError?
    guard asset.statusOfValue(forKey: "tracks", error: &error) == AVKeyValueStatus.loaded
        else { if let error = error { return print(error) } }

    readStartTimecode(asset: asset)
}


func readStartTimecode(ofAsset asset: AVAsset) {

    let timecodeTracks = asset.tracks(withMediaType: AVMediaTypeTimecode)
    guard let timecodeTrack = timecodeTracks.first,
        let assetReader = try? AVAssetReader(asset: asset) else { return }

    let readerOutput = AVAssetReaderTrackOutput(track: timecodeTrack, outputSettings: nil)
    assetReader.add(readerOutput)
    guard assetReader.startReading() else { return }

    while let sampleBuffer = readerOutput.copyNextSampleBuffer() {
        if let frame = timecodeFrame(sampleBuffer: sampleBuffer) {
            print("timecodeFrame: \(frame)")
        }
    }
}

func timecodeFrame(sampleBuffer: CMSampleBuffer) -> UInt32? {

    guard let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer),
        let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer)
        else { return nil }

    var rawData: UnsafeMutablePointer<Int8>? = nil
    var length: Int = 0
    var totalLength: Int = 0

    let status = CMBlockBufferGetDataPointer(blockBuffer, 0, &length, &totalLength, &rawData)
    guard status == kCMBlockBufferNoErr,
        let frameRead = rawData?.pointee
        else { return nil }

    let type = CMFormatDescriptionGetMediaSubType(formatDescription)

    if type == kCMTimeCodeFormatType_TimeCode32 {
        let frame = UInt32(frameRead)
        let bigFrame = CFSwapInt32BigToHost(frame)
        print("kCMTimeCodeFormatType_TimeCode32: \(bigFrame)")
    }
    if type == kCMTimeCodeFormatType_TimeCode64 {
        print("kCMTimeCodeFormatType_TimeCode64")
        // todo
    }
    return nil
}    

Edit: the Objective C version of the data pointer retrieval looks like this:

size_t length = 0;
size_t totalLength = 0;
char *rawData = NULL;

CMBlockBufferGetDataPointer(blockBuffer, 0, &length, &totalLength, &rawData);
if (status == kCMBlockBufferNoErr) {
    int32_t *frameNumberRead = (int32_t *)rawData;
    (int)Endian32_Swap(*frameNumberRead)]
}   

Solution

  • The solution is to not convert the Int8 data like UInt32(rawData.pointee) but to access the UnsafeMutablePointer<Int8> pointer's memory as a different type (temporarily). This would look like this:

    if let frames = rawData?.withMemoryRebound(to: UInt32.self, capacity: 1, { CFSwapInt32BigToHost($0.pointee) }) {
        return frames
    }
    

    The full function would look like this:

    func timecodeFrame(sampleBuffer: CMSampleBuffer) -> UInt32? {
    
        guard let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer),
            let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer)
            else { return nil }
    
        var rawData: UnsafeMutablePointer<Int8>? = nil
        var length: Int = 0
        var totalLength: Int = 0
    
        let status = CMBlockBufferGetDataPointer(blockBuffer, 0, &length, &totalLength, &rawData)
        guard status == kCMBlockBufferNoErr else { return nil }
    
        let type = CMFormatDescriptionGetMediaSubType(formatDescription)
    
        if type == kCMTimeCodeFormatType_TimeCode32 {
            if let frames = rawData?.withMemoryRebound(to: UInt32.self, capacity: 1, { CFSwapInt32BigToHost($0.pointee) }) {
                return frames
            }
        }
        if type == kCMTimeCodeFormatType_TimeCode64 {
            if let frames = rawData?.withMemoryRebound(to: UInt64.self, capacity: 1, { CFSwapInt64BigToHost($0.pointee) }) {
                return UInt32(frames)
            }
        }
        return nil
    }
    

    I hope this is useful to others who want to read the start timecode of a video's timecode track.