Skip to content

Instantly share code, notes, and snippets.

@simonkim
Created September 6, 2016 15:12
Show Gist options
  • Save simonkim/2311db75acfa25442ead2ab4d3cae06e to your computer and use it in GitHub Desktop.
Save simonkim/2311db75acfa25442ead2ab4d3cae06e to your computer and use it in GitHub Desktop.
Sample code for creating NSData backed CMBlockBuffer using customBlockAllocator, in Swift.
//
// CMBlockBufferHelper.swift
//
// Created by Simon Kim on 2016. 9. 6..
// Copyright © 2016년 DZPub.com. All rights reserved.
//
import Foundation
import CoreMedia
/**
* Sample code for creating NSData backed CMBlockBuffer using customBlockAllocator, in Swift.
*
* Example:
func testExample() {
let bytes: [UInt8] = [ 1, 2, 3, 4, 5 ]
let data = NSData(bytes: bytes, length: bytes.count)
let bb = CMBlockBufferHelper.sharedInstance.create(with: data)
XCTAssert(CMBlockBufferGetDataLength(bb!) == bytes.count)
CMBlockBufferAssureBlockMemory(bb!)
var totalLength:Int = 0
var dataPointer: UnsafeMutablePointer<Int8>? = nil
XCTAssert(CMBlockBufferGetDataPointer(bb!, 0, nil, &totalLength, &dataPointer) == noErr)
XCTAssert(totalLength == bytes.count, "totalLength \(totalLength) != \(bytes.count)")
XCTAssert(UnsafeRawPointer(dataPointer) == data.bytes, "dataPointer \(dataPointer) != \(data.bytes)")
}
*
*/
class CMBlockBufferHelper {
static var sharedInstance = {
return CMBlockBufferHelper()
}()
var holder: [NSData] = []
func retain(_ data: NSData) {
holder.append(data)
}
func release(pointer:UnsafeRawPointer) {
if let index = holder.index(where: { $0.bytes == pointer }) {
holder.remove(at: index)
}
}
func blockSource(with bytes: UnsafeMutableRawPointer) -> CMBlockBufferCustomBlockSource {
return CMBlockBufferCustomBlockSource(
version: kCMBlockBufferCustomBlockSourceVersion,
AllocateBlock: { (refCon, size) -> UnsafeMutableRawPointer? in
print("AllocateBlock:\(refCon)")
return refCon
}, FreeBlock: { (refCon, memoryBlock, size) in
print("FreeBlock:\(memoryBlock)")
CMBlockBufferHelper.sharedInstance.release(pointer:memoryBlock)
}, refCon: bytes)
}
func create(with data:NSData) -> CMBlockBuffer? {
retain(data)
var blockSource = self.blockSource(with: UnsafeMutableRawPointer(mutating: data.bytes))
var bb: CMBlockBuffer? = nil
let status = CMBlockBufferCreateWithMemoryBlock(nil, nil, data.length, nil, &blockSource, 0, data.length, 0, &bb)
if status != noErr {
print("CMBlockBufferCreateWithMemoryBlock(\(data) failed:\(status)")
release(pointer: data.bytes)
}
return bb
}
}
@xaphod
Copy link

xaphod commented Sep 26, 2018

Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment