iOS x265

x265-iOS:https://github.com/XuningZhai/x265-iOS-2.5


Code
#import <AVFoundation/AVFoundation.h>
#import "ViewController.h"
#include "x265.h"

@interface ViewController ()<AVCaptureVideoDataOutputSampleBufferDelegate>
@property (nonatomic,weak) IBOutlet UIView *viewCapture;
@property (nonatomic,weak) IBOutlet UIButton *btnOutput;
@property (nonatomic,strong) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
@property (nonatomic,strong) AVCaptureSession *captureSession;
@property (nonatomic,strong) AVCaptureConnection *captureVideoConnection;
@property (strong) NSMutableArray *yuv420Frames;
@property (strong) NSMutableData *dataX265;
@property (nonatomic,assign) x265_param *x265Param;
@property (nonatomic,assign) x265_encoder *x265Encoder;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initData];
    [self initCapture];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self start];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self stop];
}

- (void)initData
{
    [self setYuv420Frames:[NSMutableArray array]];
    [self setDataX265:[NSMutableData data]];
    int width = 352;
    int height = 288;
    self.x265Param = x265_param_alloc();
    x265_param_default(self.x265Param);
    self.x265Param->bRepeatHeaders = 1;
    self.x265Param->internalCsp = X265_CSP_I420;
    self.x265Param->sourceWidth = width;
    self.x265Param->sourceHeight = height;
    self.x265Param->fpsNum = 18;
    self.x265Param->fpsDenom = 1;
    self.x265Encoder = x265_encoder_open(self.x265Param);
}

- (void)initCapture
{
    self.captureSession = [[AVCaptureSession alloc] init];
    AVCaptureDevice* inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:nil];
    [self.captureSession addInput:captureInput];
    AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
    [captureOutput setAlwaysDiscardsLateVideoFrames:YES];
    [captureOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];
    NSString* key = (NSString *)kCVPixelBufferPixelFormatTypeKey;
    //Pixel Format NV12
    NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange];
    NSDictionary *videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
    [captureOutput setVideoSettings:videoSettings];
    [self.captureSession setSessionPreset:AVCaptureSessionPreset352x288];
    [self.captureSession addOutput:captureOutput];
    [self setCaptureVideoConnection:[captureOutput connectionWithMediaType:AVMediaTypeVideo]];
    [self setCaptureVideoPreviewLayer:[AVCaptureVideoPreviewLayer layerWithSession:self.captureSession]];
    [self.captureVideoPreviewLayer setFrame:self.view.bounds];
    [self.captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
    [self.captureVideoPreviewLayer connection];
    [self.viewCapture.layer addSublayer:self.captureVideoPreviewLayer];
}

- (void)start
{
    [self.captureSession startRunning];
}

- (void)stop
{
    [self.captureSession stopRunning];
}

- (IBAction)outputX265Video:(id)sender
{
    [self.captureSession stopRunning];
    dispatch_async(dispatch_queue_create("x265_queue", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, -1)), ^{
        while ([self.yuv420Frames count] != 0)
        {
            NSData *yuv420Frame = [self.yuv420Frames firstObject];
            [self encodeX265FromYuv420Frame:yuv420Frame];
            [self.yuv420Frames removeObject:yuv420Frame];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *title = [NSString stringWithFormat:@"remaining encode frames:%ld", [self.yuv420Frames count]];
                [self.btnOutput setTitle:title forState:UIControlStateNormal];
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *docDir = [paths objectAtIndex:0];
            NSString *recordX265VideoPath = [docDir stringByAppendingPathComponent:@"test265.hevc"];
            if([[NSFileManager defaultManager] fileExistsAtPath:recordX265VideoPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:recordX265VideoPath error:nil];
            }
            [self.dataX265 writeToFile:recordX265VideoPath atomically:YES];
            [self.btnOutput setTitle:@"finish" forState:UIControlStateNormal];
        });
    });
}

- (void)dealloc
{
    if (self.x265Encoder)
    {
        x265_encoder_close(self.x265Encoder);
    }
    if (self.x265Param)
    {
        x265_param_free(self.x265Param);
    }
}

#pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    if (connection == self.captureVideoConnection)
    {
        CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
        if (CVPixelBufferLockBaseAddress(imageBuffer, 0) == kCVReturnSuccess)
        {
            OSType pixelFormat = CVPixelBufferGetPixelFormatType(imageBuffer);
            switch (pixelFormat)
            {
                case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
                {
                    //Capture pixel format is NV12, convert to yuv420
                    NSData *yuv420Frame = [self convertYUV420FromNV12ImageBuffer:imageBuffer];
                    [self.yuv420Frames addObject:yuv420Frame];
                }
                break;
            }
        }
        CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
    }
}

- (NSData*)convertYUV420FromNV12ImageBuffer:(CVPixelBufferRef)imageBuffer
{
    UInt8 *bufferPtr = (UInt8 *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer,0);
    UInt8 *bufferPtr1 = (UInt8 *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer,1);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    size_t bytesrow0 = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer,0);
    size_t bytesrow1  = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer,1);
    size_t yuv420_len = sizeof(UInt8) * width * height * 3 / 2;
    //buffer to store YUV with layout YYYYYYYYUUVV
    UInt8 *yuv420_data = malloc(yuv420_len);
    //convert NV12 data to YUV420
    UInt8 *pY = bufferPtr ;
    UInt8 *pUV = bufferPtr1;
    UInt8 *pU = yuv420_data + width * height;
    UInt8 *pV = pU + width * height / 4;
    for(int i = 0; i < height; i++)
    {
        memcpy(yuv420_data + i * width, pY + i * bytesrow0, width);
    }
    for(int j = 0; j < height / 2; j++)
    {
        for(int i =0; i < width / 2; i++)
        {
            *(pU++) = pUV[i << 1];
            *(pV++) = pUV[(i << 1) + 1];
        }
        pUV += bytesrow1;
    }
    NSData *yuv420Frame = [NSData dataWithBytes:yuv420_data length:yuv420_len];
    free(yuv420_data);
    return yuv420Frame;
}

- (void)encodeX265FromYuv420Frame:(NSData*)yuv420Frame
{
    UInt8 *yuv420_buf = (UInt8*)yuv420Frame.bytes;
    //encode x265
    x265_picture *x265Pic = NULL;
    char *x265PicBuf = NULL;
    int width = self.x265Param->sourceWidth;
    int height = self.x265Param->sourceHeight;
    int pixeSize = width * height;
    x265Pic = x265_picture_alloc();
    x265_picture_init(self.x265Param, x265Pic);
    x265PicBuf = malloc(sizeof(char) * pixeSize * 3 / 2);
    x265Pic->planes[0] = x265PicBuf;
    x265Pic->planes[1] = x265PicBuf + pixeSize;
    x265Pic->planes[2] = x265PicBuf + pixeSize * 5 / 4;
    x265Pic->stride[0] = width;
    x265Pic->stride[1] = width / 2;
    x265Pic->stride[2] = width / 2;
    memcpy(x265Pic->planes[0], yuv420_buf, pixeSize);
    memcpy(x265Pic->planes[1], yuv420_buf + pixeSize, pixeSize / 4);
    memcpy(x265Pic->planes[2], yuv420_buf + pixeSize * 5 / 4, pixeSize / 4);
    x265_nal *x265NalPp = NULL;
    uint32_t x265NalPi = 0;
    x265_encoder_encode(self.x265Encoder, &x265NalPp, &x265NalPi, x265Pic, NULL);
    for (int i = 0; i < x265NalPi; i++)
    {
        uint8_t* payload = x265NalPp[i].payload;
        uint32_t sizeBytes = x265NalPp[i].sizeBytes;
        [self.dataX265 appendBytes:payload length:sizeBytes];
    }
    x265_encoder_encode(self.x265Encoder, &x265NalPp, &x265NalPi, NULL, NULL);
    for (int i = 0; i < x265NalPi; i++)
    {
        uint8_t* payload = x265NalPp[i].payload;
        uint32_t sizeBytes = x265NalPp[i].sizeBytes;
        [self.dataX265 appendBytes:payload length:sizeBytes];
    }
    x265_picture_free(x265Pic);
    free(x265PicBuf);
}



@end

参考:https://www.jianshu.com/p/30a2486e4ab6

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容