在iOS上使用HEVC编码器输出视频大小很大

问题描述 投票:3回答:1

我有一个项目,目前使用H.264编码器在iOS上录制视频。我想尝试在iOS 11中使用新的HEVC编码器来减小文件大小,但是发现使用HEVC编码器会导致文件大小膨胀。 Here's a project on GitHub that shows the issue - it simultaneously writes frames from the camera to files using the H.264 and H.265 (HEVC) encoders, and the resulting file sizes are printed to the console.

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)")
        }
    }
...

然后帧写成这样:

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

因为他们进入了AVCaptureVideoDataOutputSampleBufferDelegate。根据我录制的质量(720p或1080p),HEVC编码视频的文件大小应该是相同H.264编码视频的40-60%,我在使用默认相机应用程序时看到这一点iOS,但是当我使用上面的AVAssetWriter时(或上面链接的项目中),我看到HEVC的文件大小比H.264大三倍。要么我做错了,要么HEVC编码器工作不正常。我是否遗漏了某些东西,或者是否有办法让HEVC通过AVFoundation工作?

ios swift avfoundation avassetwriter hevc
1个回答
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];
...

据我所知,使用相同的比特率,H264和HEVC的文件大小应相同,但HEVC的质量应该更好。

© www.soinside.com 2019 - 2024. All rights reserved.