在 iOS 上使用 HEVC 编码器输出视频尺寸巨大

jpe*_*hsr 5 avfoundation ios avassetwriter hevc swift

我有一个项目,目前使用 H.264 编码器在 iOS 上录制视频。我想尝试在 iOS 11 中使用新的 HEVC 编码器来减小文件大小,但发现使用 HEVC 编码器会导致文件大小急剧膨胀。 GitHub 上的一个项目显示了该问题 - 它使用 H.264 和 H.265 (HEVC) 编码器同时将相机中的帧写入文件,并将生成的文件大小打印到控制台。

AVFoundation 类的设置如下:

class VideoWriter {
    var avAssetWriterInput: AVAssetWriterInput
    var avAssetWriter: AVassetWriter
    init() {
        if #available(iOS 11.0, *) {
            avAssetWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: [AVVideoCodecKey:AVVideoCodecType.hevc, AVVideoHeightKey:720, AVVideoWidthKey:1280])
        }
        avAssetWriterInput.expectsMediaDataInRealTime = true
        do {
            let url = directory.appendingPathComponent(UUID.init().uuidString.appending(".hevc"))
            avAssetWriter = try AVAssetWriter(url: url, fileType: AVFileType.mp4)
            avAssetWriter.add(avAssetWriterInput)
            avAssetWriter.movieFragmentInterval = kCMTimeInvalid
        } catch {
            fatalError("Could not initialize AVAssetWriter \(error)")
        }
    }
...
Run Code Online (Sandbox Code Playgroud)

然后框架是这样写的:

    func write(sampleBuffer buffer: CMSampleBuffer) {
        if avAssetWriter.status == AVAssetWriterStatus.unknown {
            avAssetWriter.startWriting()
            avAssetWriter.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(buffer))
         }
        if avAssetWriterInput.isReadyForMoreMediaData {
            avAssetWriterInput.append(buffer)
        }
    }
Run Code Online (Sandbox Code Playgroud)

当他们进来的时候AVCaptureVideoDataOutputSampleBufferDelegate。按照我录制的质量(720p 或 1080p),HEVC 编码视频的文件大小应为相同 H.264 编码视频的 40-60%,当我使用默认相机应用程序时,我会看到这一点iOS,但是当我如上所述使用 AVAssetWriter(或在上面链接的项目中)时,我发现 HEVC 的文件大小比 H.264 大大约三倍。要么是我做错了什么,要么是 HEVC 编码器无法正常工作。我是否遗漏了某些内容,或者是否有解决方法可以让 HEVC 通过 AVFoundation 工作?

小智 2

您是否尝试过指定比特率等?如下:

NSUInteger bitrate = 50 * 1024 * 1024;  // 50 Mbps
NSUInteger keyFrameInterval = 30;
NSString *videoProfile = AVVideoProfileLevelH264HighAutoLevel;
NSString *codec = AVVideoCodecH264;
if (@available(iOS 11, *)) {
    videoProfile = (NSString *)kVTProfileLevel_HEVC_Main_AutoLevel;
    codec = AVVideoCodecTypeHEVC;
}

NSDictionary *codecSettings = @{AVVideoAverageBitRateKey: @(bitrate),
                              AVVideoMaxKeyFrameIntervalKey: @(keyFrameInterval),
                              AVVideoProfileLevelKey: videoProfile};
NSDictionary *videoSettings = @{AVVideoCodecKey: codec,
                              AVVideoCompressionPropertiesKey: codecSettings,
                              AVVideoWidthKey: @((NSInteger)resolution.width),
                              AVVideoHeightKey: @((NSInteger)resolution.height)};

AVAssetWriterInput *videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
...
Run Code Online (Sandbox Code Playgroud)

据我了解,在相同的比特率下,H264和HEVC的文件大小应该相同,但HEVC的质量应该更好。