Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a VTCompressionSession in swift?

I have been looking high and low for how to create a VTCompressionSession (in swift) as briefly mentioned in the 2014 WWDC Video - 'Direct Access to Video Encoding and Decoding'.

The following code works in Objective-C:

#import <Foundation/Foundation.h>
#import <VideoToolbox/VideoToolbox.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        VTCompressionSessionRef session;
        VTCompressionSessionCreate(NULL, 500, 500, kCMVideoCodecType_H264, NULL, NULL, NULL, NULL, NULL, &session);

        NSLog(@"created VTCompressionSession");
    }
    return 0;
}

But no matter what I have tried I cannot find a way to import VTCompressionSessionCreate to swift.

import Foundation
import VideoToolbox

VideoToolbox.VTCompressionSessionCreate()

println("created VTCompressionSession")

This code for instance breaks with: Module 'VideoToolbox' has no member named 'VTCompressionSessionCreate'.
Just calling VTCompressionSessionCreate creates the error message Use of unresolved identifier 'VTCompressionSessionCreate'.

It looks like it the API is not exposed in swift, since I can call methods like VTCompressionSessionEncodeFrame just fine. Am I missing something obvious?

like image 613
Marco Pashkov Avatar asked Oct 21 '22 07:10

Marco Pashkov


1 Answers

My workaround is to write an objective-c function and expose it via a bridging-header to swift:

Compression.h

#import <VideoToolbox/VideoToolbox.h>
VTCompressionSessionRef CreateCompressionSession();

Compression.m

#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#import <VideoToolbox/VideoToolbox.h>

VTCompressionSessionRef CreateCompressionSession(){
    NSLog(@"CreateCompressionSession");
    VTCompressionSessionRef session;
    VTCompressionSessionCreate(NULL, 500, 500, kCMVideoCodecType_H264, NULL, NULL, NULL, NULL, NULL, &session);
    return session;
}

stream-Bridging-Header.h

#import "CompressionSession.h"

Now you can run the following code in swift:

import Cocoa
import Foundation
import VideoToolbox

let session = CreateCompressionSession()
like image 159
Marco Pashkov Avatar answered Oct 27 '22 13:10

Marco Pashkov