用ffmpeg來處理音視頻格式問題以及錄屏的裸數(shù)據(jù)轉mp4

文章是以實現(xiàn)iOS12+的錄屏功能(RPSystemBroadcastPickerView)來進行闡述遇到的問題,后續(xù)也會繼續(xù)補充相關技術點。方式是利用添加擴展(RPBroadcastSampleHandler)的方式來實現(xiàn)錄屏功能,進而闡述如何使用ffmpeg進行視頻格式的轉碼。本文難點有兩點:1,擴展中獲取到的原始數(shù)據(jù)CMSampleBufferRef如何傳遞到宿主App;2,宿主App接收到擴展(SampleHandler)傳遞的視頻流如何對其進行硬編碼,最后實現(xiàn)格式轉碼。

添加擴展,調(diào)取系統(tǒng)錄屏的方法

添加擴展

自動生成的擴展文件
  • 錄屏的方法
// 開始錄屏
- (void)broadcastStartedWithSetupInfo:(NSDictionary<NSString *,NSObject *> *)setupInfo {

//    // 監(jiān)聽 綁定socket
    [[HYLocalServerBufferSocketManager defaultManager] setupSocket];

    // 開始錄屏時發(fā)出通知
    [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];
}

// 這個方法是實時獲取錄屏直播,所以不要在這個方法中寫發(fā)通知(同步),會造成線程阻塞的問題
- (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";
        }
        // 間接移除系統(tǒng)錄屏自帶的錄屏按鈕
        for (UIView *view in broadcastPickerView.subviews) {
            if ([view isKindOfClass:[UIButton class]])  {
                [(UIButton*)view sendActionsForControlEvents:UIControlEventTouchUpInside];
            }
        }
    }

上面就正式完成了iOS12+喚起系統(tǒng)自帶錄屏功能的擴展及調(diào)用方式

數(shù)據(jù)傳遞方式

  • local socket
  • 通知(CFNotificationCenterRef)// 進程間的通知方式,由于擴展和宿主App分別是兩個獨立的運行模塊,所以是兩個進程。
  • App Group

注意點:利用CFNotificationCenterRef的方式傳遞數(shù)據(jù)時,無法傳遞實時采集的原始數(shù)據(jù), 所以我這里利用通知來傳遞錄屏的狀態(tài), 有可能是自己方式不對,后續(xù)繼續(xù)深入去了解... 。

方式一:通知方式傳遞
void NotificationCallback(CFNotificationCenterRef center,
                                   void * observer,
                                   CFStringRef name,
                                   void const * object,
                                   CFDictionaryRef userInfo) {
    NSString *identifier = (__bridge NSString *)name;
    NSObject *sender = (__bridge NSObject *)observer;
    // 使用通知打印的userInfo為空, 這里我傳的是采集的原始幀數(shù)據(jù)
//    NSDictionary *info = (__bridge NSDictionary *)userInfo;
//    NSDictionary *infoss= CFBridgingRelease(userInfo);
    NSDictionary *notiUserInfo = @{@"identifier":identifier};
    [[NSNotificationCenter defaultCenter] postNotificationName:ScreenHoleNotificationName
                                                        object:sender
                                                      userInfo:notiUserInfo];
}
方式二:local socket

這種方式是參照阿里云的智能雙錄質(zhì)檢的幫助中心 iOS屏幕共享使用說明的文檔。socket是一對套接字,服務端的套接字運行在擴展中,客戶端的套接字運行在宿主App中。服務端的socket會先將CMSampleBufferRef轉為 CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);最后利用NTESI420FrameCVPixelBufferRef轉為NSData發(fā)給對應得Host App的socket。

  • 1,創(chuàng)建服務端和客戶端的socket。
  • 2,服務端的socket將采集到的CMSampleBufferRef原始幀視頻轉為NSData格式發(fā)給客戶端的socket。
  • 3,客戶端的socket接收到數(shù)據(jù)后再對數(shù)據(jù)進行解碼得到原始幀數(shù)據(jù)CMSampleBufferRef。

利用ffmpeg進行裸幀數(shù)據(jù)的格式編碼

  • 安裝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,進入文件執(zhí)行下列命令
./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"
  • 第三部:配置靜態(tài)庫等文件


    配置靜態(tài)庫等文件
  • 第四部: 添加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幀數(shù)目控制,-g 關鍵幀間隔控制,-s 分辨率控制

思路解析
我們在添加擴展后拿到的一般是CMSampleBufferRef格式的原始數(shù)據(jù),而這種格式的數(shù)據(jù)不能進行進程間的直接傳遞,以及播放。所以需要進行處理和轉碼。
1,將CMSampleBufferRef格式轉為.264(NSData)的格式
2,可以使用ffmpeg的轉碼將.264(NSData)轉為MP4,需要注意的是設置的size,不對的話,可能會造成視頻的拉伸或擠壓。

將CMSampleBufferRef格式的幀數(shù)據(jù)轉成mp4,并保存到沙盒中

思路:

  • 1,利用socket、通知、AppGroup的方式將擴展中中實時采集的幀數(shù)據(jù)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不能傳遞錄屏的數(shù)據(jù),所以在項目中使用通知是監(jiān)聽錄屏的狀態(tài)statussocket的方式需要用到GCDAsyncSocket,在套接字之間傳的是NTESI420Frame轉化的NSData,最后再轉回為CMSampleBufferRef。類似剪映等產(chǎn)品的錄屏應該都是使用AVAssetWriter、AVAssetWriterInput、AVAssetWriterInputPixelBufferAdaptor、AVCaptureSession來處理原始的幀數(shù)據(jù)后保存到沙盒中。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容