GStreamer 是一個相當重量級的串流媒體開發框架,但中文資料不多。以下內容整理自官方 Tutorial 系列,一方面希望讓有興趣的開發者快速上手,另一方面也當作自己的學習筆記。專有名詞保留英文,方便對照官方文件。
第一個 iOS 教程非常簡單:取得 GStreamer 的版本資訊並顯示在畫面上。重點不是功能,而是示範在 Xcode 專案中正確連結 GStreamer 的函式庫。
範例專案是以 GStreamer Single View Application 模板產生的,實際程式碼可於安裝包中找到。畫面裡只有一個用來顯示版本的 UILabel。
使用 storyboard 呈現單一視圖,中間擺一個居中的 UILabel,並在 ViewController 中建立對應的 IBOutlet。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UILabel *label;
}
@property (retain, nonatomic) UILabel *label;
@end
所有 GStreamer 相關程式碼都集中在名為 GStreamerBackend 的 Objective-C 類別中。後續教程這個類別會逐步長大,目前只有一個取得版本的方法。
由於 GStreamer 本身是以 C 撰寫,這個封裝層同時肩負 C 與 Objective-C 之間的轉換工作,作用有點類似 Android 版本上的 JNI。有了它,UI 層呼叫起來乾淨得多。
#import "GStreamerBackend.h"
#include <gst/gst.h>
@implementation GStreamerBackend
- (NSString *)getGStreamerVersion {
char *version_utf8 = gst_version_string();
NSString *version_string = [NSString stringWithUTF8String:version_utf8];
g_free(version_utf8);
return version_string;
}
@end
這裡的 g_free 值得留意:gst_version_string() 回傳的是由 GLib 配置的字串,必須以 g_free 釋放,不能用 free 或 ARC。C 與 Objective-C 混用時,記憶體必須由「配置它的那一側」負責釋放,這條原則一路適用到 Core Foundation 物件。
#import "ViewController.h"
#import "GStreamerBackend.h"
@interface ViewController () {
GStreamerBackend *gst_backend;
}
@end
@implementation ViewController
@synthesize label;
- (void)viewDidLoad {
[super viewDidLoad];
gst_backend = [[GStreamerBackend alloc] init];
label.text = [NSString stringWithFormat:@"Welcome to %@!",
[gst_backend getGStreamerVersion]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
第一個教程到此結束。它想傳達的訊息是:因為 C 與 Objective-C 的互通性,把 GStreamer 用在 iOS 上,難度和用在桌面應用上差不多。为了程式碼的清晰度而加入的 GStreamerBackend 封裝並非必要,直接在應用中呼叫 framework 也走得通;但當功能開始變多、需要管理 pipeline 生命週期與 delegate 回呼時,這個分層會回報你的投資。