用ffmpeg来处理音视频格式问题以及录屏的裸数据转mp4

文章是以实现iOS12+的录屏功能(RPSystemBroadcastPickerView)来进行阐述遇到的问题,后续也会继续补充相关技术点。方式是利用添加扩展(RPBroadcastSampleHandler)的方式来实现录屏功能,进而阐述如何使用ffmpeg进行视频格式的转码。本文难点有两点:1,扩展中获取到的原始数据CMSampleBufferRef如何传递到宿主App;2,宿主App接收到扩展(SampleHandler)传递的视频流如何对其进行硬编码,最后实现格式转码。

添加扩展,调取系统录屏的方法

添加扩展

自动生成的扩展文件
  • 录屏的方法
// 开始录屏
- (void)broadcastStartedWithSetupInfo:(NSDictionary<NSString *,NSObject *> *)setupInfo {

//    // 监听 绑定socket
    [[HYLocalServerBufferSocketManager defaultManager] setupSocket];

    // 开始录屏时发出通知
    [self sendNotificationForMessageWithIdentifier:@"broadcastStartedWithSetupInfo" userInfo:nil];
}

// 暂停录屏
- (void)broadcastPaused {

    [[HYLocalServerBufferSocketManager defaultManager] disConnectSocket];
    [self sendNotificationForMessageWithIdentifier:@"broadcastPaused" userInfo:nil];
}

// 恢复录屏
- (void)broadcastResumed {

    [[HYLocalServerBufferSocketManager defaultManager] disConnectSocket];
    [self sendNotificationForMessageWithIdentifier:@"broadcastResumed" userInfo:nil];
}

// 结束录屏
- (void)broadcastFinished {

    [[HYLocalServerBufferSocketManager defaultManager] disConnectSocket];
    [self sendNotificationForMessageWithIdentifier:@"broadcastFinished" userInfo:nil];
}

// 这个方法是实时获取录屏直播,所以不要在这个方法中写发通知(同步),会造成线程阻塞的问题
- (void)processSampleBuffer:(CMSampleBufferRef)sampleBuffer withType:(RPSampleBufferType)sampleBufferType {
    switch (sampleBufferType) {
        case RPSampleBufferTypeVideo:
            @autoreleasepool { 
                [[HYLocalServerBufferSocketManager defaultManager] sendVideoBufferToHostApp:sampleBuffer];
            }
            break;
        case RPSampleBufferTypeAudioApp:
            break;
        case RPSampleBufferTypeAudioMic:
            // Handle audio sample buffer for mic audio
            break;
            
        default:
            break;
    }
}
  • 录屏的唤起方法
    if (@available(iOS 12.0, *)) {

        RPSystemBroadcastPickerView *broadcastPickerView = [[RPSystemBroadcastPickerView alloc] initWithFrame: [UIScreen mainScreen].bounds];
        broadcastPickerView.showsMicrophoneButton = YES;
        //你的app对用upload extension的 bundle id, 必须要填写对
        if (@available(iOS 12.0, *)) {
            broadcastPickerView.preferredExtension = @"com.hyTechnology.ffmpegDemo.XIBOBroadcastUploadExtension";
        }
        // 间接移除系统录屏自带的录屏按钮
        for (UIView *view in broadcastPickerView.subviews) {
            if ([view isKindOfClass:[UIButton class]])  {
                [(UIButton*)view sendActionsForControlEvents:UIControlEventTouchUpInside];
            }
        }
    }

上面就正式完成了iOS12+唤起系统自带录屏功能的扩展及调用方式

数据传递方式

  • local socket
  • 通知(CFNotificationCenterRef)// 进程间的通知方式,由于扩展和宿主App分别是两个独立的运行模块,所以是两个进程。
  • App Group

注意点:利用CFNotificationCenterRef的方式传递数据时,无法传递实时采集的原始数据, 所以我这里利用通知来传递录屏的状态, 有可能是自己方式不对,后续继续深入去了解... 。

方式一:通知方式传递
void NotificationCallback(CFNotificationCenterRef center,
                                   void * observer,
                                   CFStringRef name,
                                   void const * object,
                                   CFDictionaryRef userInfo) {
    NSString *identifier = (__bridge NSString *)name;
    NSObject *sender = (__bridge NSObject *)observer;
    // 使用通知打印的userInfo为空, 这里我传的是采集的原始帧数据
//    NSDictionary *info = (__bridge NSDictionary *)userInfo;
//    NSDictionary *infoss= CFBridgingRelease(userInfo);
    NSDictionary *notiUserInfo = @{@"identifier":identifier};
    [[NSNotificationCenter defaultCenter] postNotificationName:ScreenHoleNotificationName
                                                        object:sender
                                                      userInfo:notiUserInfo];
}
方式二:local socket

这种方式是参照阿里云的智能双录质检的帮助中心 iOS屏幕共享使用说明的文档。socket是一对套接字,服务端的套接字运行在扩展中,客户端的套接字运行在宿主App中。服务端的socket会先将CMSampleBufferRef转为 CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);最后利用NTESI420FrameCVPixelBufferRef转为NSData发给对应得Host App的socket。

  • 1,创建服务端和客户端的socket。
  • 2,服务端的socket将采集到的CMSampleBufferRef原始帧视频转为NSData格式发给客户端的socket。
  • 3,客户端的socket接收到数据后再对数据进行解码得到原始帧数据CMSampleBufferRef

利用ffmpeg进行裸帧数据的格式编码

  • 安装ffmpeg
1, 安装过程Homebrew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

2, 安装 gas-preprocessor
sudo git clone https://github.com/bigsen/gas-preprocessor.git /usr/local/bin/gas
sudo cp /usr/local/bin/gas/gas-preprocessor.pl /usr/local/bin/gas-preprocessor.pl
sudo chmod 777 /usr/local/bin/gas-preprocessor.pl
sudo rm -rf /usr/local/bin/gas/

3, 安装 yams
brew info yasm

4, 下载ffmpeg
brew install ffmpeg

5,进入文件执行下列命令
./build-ffmpeg.sh

注意: 再install ffmpeg的时候可能会失败(eg:下图1),按照提示install 即可,成功之后重新install ffmpeg

install ffmpeg 失败 1
安装成功后自动生成的文件

iOS集成ffmpeg

当我们下载ffmpeg脚本后进入文件夹使用./build-ffmpeg.sh就会自动生成FFmpeg-iOS等文件(如下图)

编译过后生成的ffmpeg文件

  • 第一步:将FFmpeg-iOS文件夹拖进工程
  • 第二步:配置头文件的搜索路径在工程文件->Bulid Setting->Search Paths->Header Search Paths添加"$(SRCROOT)/ffmpegDemo/FFmpeg-iOS/include"
  • 第三部:配置静态库等文件


    配置静态库等文件
  • 第四部: 添加fftools文件夹,tools文件中不是所有的都需要,按自己需求添加


    fftools
  • 第五步:#import "ffmpeg.h"并在工程中写入av_register_all();后?commond+B编译一下,这里会某些文件找不到的报错,可直接到编译后的脚本文件夹中
例如:config.h文件找不到,可以到下图的文件夹中添加即可,其他同理
#include "libavutil/thread.h"
#include "libavutil/reverse.h"
#include "libavutil/libm.h"
#include "libpostproc/postprocess.h"
#include "libpostproc/version.h"
#include "libavformat/os_support.h"
#include "libavcodec/mathops.h"
#include "libavresample/avresample.h"
#include "compat/va_copy.h" 
#include "libavutil/internal.h"
编译文件中的config文件

如果项目不要用到相关的文件,可以直接注释错误
eg: // #include "libavutil/internal.h"

ffmpeg的格式转换

    NSString *fromFile = [[NSBundle mainBundle]pathForResource:@"videp.mp4" ofType:nil];
    
    NSString *toFile = @"/Users/Alex/output/source/video.gif";
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:toFile]) {
        [fileManager removeItemAtPath:toFile error:nil];
    }
    char *a[] = {
        "ffmpeg", "-i", (char *)[fromFile UTF8String], (char *)[toFile UTF8String]
    };

    int result = ffmpeg_main(sizeof(a)/sizeof(*a), a);
    NSLog(@"这是结果 %d",result);
或

ffmpeg –i test.mp4 –vcodec h264 –s 352*278 –an –f m4v video.264              //转码为码流原始文件
ffmpeg –i test.mp4 –vcodec h264 –bf 0 –g 25 –s 352*278 –an –f m4v video.264  //转码为码流原始文件
ffmpeg –i test.avi -vcodec mpeg4 –vtag xvid –qsame test_xvid.avi            //转码为封装文件
//-bf B帧数目控制,-g 关键帧间隔控制,-s 分辨率控制

思路解析
我们在添加扩展后拿到的一般是CMSampleBufferRef格式的原始数据,而这种格式的数据不能进行进程间的直接传递,以及播放。所以需要进行处理和转码。
1,将CMSampleBufferRef格式转为.264(NSData)的格式
2,可以使用ffmpeg的转码将.264(NSData)转为MP4,需要注意的是设置的size,不对的话,可能会造成视频的拉伸或挤压。

将CMSampleBufferRef格式的帧数据转成mp4,并保存到沙盒中

思路:

  • 1,利用socket、通知、AppGroup的方式将扩展中中实时采集的帧数据CMSampleBufferRef传递到宿主App中


    Snip20210912_9.png
  • 2,利用AVCaptureSession、AVAssetWriter、AVAssetWriterInput将CMSampleBufferRef转为mp4, 并[图片上传中...(Snip20210912_7.png-aa8236-1631443458420-0)]
    利用NSFileManger保存到指定沙盒

- (void)startScreenRecording {
    
    self.captureSession = [[AVCaptureSession alloc]init];
    self.screenRecorder = [RPScreenRecorder sharedRecorder];
    if (self.screenRecorder.isRecording) {
        return;
    }
    NSError *error = nil;
    NSArray *pathDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *outputURL = pathDocuments[0];
    self.videoOutPath = [[outputURL stringByAppendingPathComponent:@"demo是嗯嗯嗯是是"] stringByAppendingPathExtension:@"mp4"];
    NSLog(@"self.videoOutPath=%@",self.videoOutPath);
    
    self.assetWriter = [AVAssetWriter assetWriterWithURL:[NSURL fileURLWithPath:self.videoOutPath] fileType:AVFileTypeMPEG4 error:&error];
    
    NSDictionary *compressionProperties =
        @{AVVideoProfileLevelKey         : AVVideoProfileLevelH264HighAutoLevel,
          AVVideoH264EntropyModeKey      : AVVideoH264EntropyModeCABAC,
          AVVideoAverageBitRateKey       : @(1920 * 1080 * 11.4),
          AVVideoMaxKeyFrameIntervalKey  : @60,
          AVVideoAllowFrameReorderingKey : @NO};
    
    NSNumber* width= [NSNumber numberWithFloat:[[UIScreen mainScreen] bounds].size.width];
    NSNumber* height = [NSNumber numberWithFloat:[[UIScreen mainScreen] bounds].size.height];
    
    NSDictionary *videoSettings =
        @{
          AVVideoCompressionPropertiesKey : compressionProperties,
          AVVideoCodecKey                 : AVVideoCodecTypeH264,
          AVVideoWidthKey                 : width,
          AVVideoHeightKey                : height
          };
    
    self.assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
    self.pixelBufferAdaptor =
    [[AVAssetWriterInputPixelBufferAdaptor alloc]initWithAssetWriterInput:self.assetWriterInput
                                              sourcePixelBufferAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA],kCVPixelBufferPixelFormatTypeKey,nil]];
    [self.assetWriter addInput:self.assetWriterInput];
    [self.assetWriterInput setMediaTimeScale:60];
    [self.assetWriter setMovieTimeScale:60];
    [self.assetWriterInput setExpectsMediaDataInRealTime:YES];
    
    //写入视频
    [self.assetWriter startWriting];
    [self.assetWriter startSessionAtSourceTime:kCMTimeZero];
    
    [self.captureSession startRunning];
    
}
  • 3,开始录屏时初始化assetWriter,结束录屏时进行写入完成操作


    初始化assetWriter和完成

总结

整个过程中最简单的方式还是使用AppGroup的方式进行进程间的传值操作,通知方式CFNotificationCenterRef不能传递录屏的数据,所以在项目中使用通知是监听录屏的状态statussocket的方式需要用到GCDAsyncSocket,在套接字之间传的是NTESI420Frame转化的NSData,最后再转回为CMSampleBufferRef。类似剪映等产品的录屏应该都是使用AVAssetWriter、AVAssetWriterInput、AVAssetWriterInputPixelBufferAdaptor、AVCaptureSession来处理原始的帧数据后保存到沙盒中。

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

推荐阅读更多精彩内容