將編碼的視頻流解碼爲原始視頻數據,編碼視頻流能夠來自網絡流或文件,解碼後便可渲染到屏幕.git
正如咱們所知,編碼數據僅用於傳輸,沒法直接渲染到屏幕上,因此這裏利用FFmpeg解析文件中的編碼的視頻流,並將壓縮視頻數據(h264/h265)解碼爲指定格式(yuv,RGB)的視頻原始數據,以渲染到屏幕上.github
注意: 本例主要爲解碼,須要藉助FFmpeg搭建模塊,視頻解析模塊,渲染模塊,這些模塊在下面閱讀前提皆有連接可直接訪問.bash
FFmpeg parse流程網絡
avformat_alloc_context
avformat_open_input
avformat_find_stream_info
formatContext->streams[i]->codecpar->codec_type == (isVideoStream ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO)
m_formatContext->streams[m_audioStreamIndex]
av_read_frame
av_bitstream_filter_filter
FFmpeg decode流程架構
enum AVHWDeviceType av_hwdevice_find_type_by_name(const char *name)
int av_find_best_stream(AVFormatContext *ic,enum FfmpegaVMediaType type,int wanted_stream_nb,int related_stream,AVCodec **decoder_ret,int flags);
AVCodecContext *avcodec_alloc_context3(const AVCodec *codec)
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par);
int av_hwdevice_ctx_create(AVBufferRef **device_ctx, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int flags)
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
AVFrame *av_frame_alloc(void)
packet.flags == 1
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
CVPixelBufferRef
並將其轉爲CMSampleBufferRef
,解碼完成- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
- (void)setupUI {
self.previewView = [[XDXPreviewView alloc] initWithFrame:self.view.frame];
[self.view addSubview:self.previewView];
[self.view bringSubviewToFront:self.startBtn];
}
複製代碼
- (void)startDecodeByFFmpegWithIsH265Data:(BOOL)isH265 {
NSString *path = [[NSBundle mainBundle] pathForResource:isH265 ? @"testh265" : @"testh264" ofType:@"MOV"];
XDXAVParseHandler *parseHandler = [[XDXAVParseHandler alloc] initWithPath:path];
XDXFFmpegVideoDecoder *decoder = [[XDXFFmpegVideoDecoder alloc] initWithFormatContext:[parseHandler getFormatContext] videoStreamIndex:[parseHandler getVideoStreamIndex]];
decoder.delegate = self;
[parseHandler startParseGetAVPackeWithCompletionHandler:^(BOOL isVideoFrame, BOOL isFinish, AVPacket packet) {
if (isFinish) {
[decoder stopDecoder];
return;
}
if (isVideoFrame) {
[decoder startDecodeVideoDataWithAVPacket:packet];
}
}];
}
複製代碼
-(void)getDecodeVideoDataByFFmpeg:(CMSampleBufferRef)sampleBuffer {
CVPixelBufferRef pix = CMSampleBufferGetImageBuffer(sampleBuffer);
[self.previewView displayPixelBuffer:pix];
}
複製代碼
由於本例中的視頻數據源是文件,而format context上下文實在parse模塊初始化的,因此這裏僅僅須要將其傳入解碼器便可.框架
- (instancetype)initWithFormatContext:(AVFormatContext *)formatContext videoStreamIndex:(int)videoStreamIndex {
if (self = [super init]) {
m_formatContext = formatContext;
m_videoStreamIndex = videoStreamIndex;
m_isFindIDR = NO;
m_base_time = 0;
[self initDecoder];
}
return self;
}
複製代碼
- (void)initDecoder {
// 獲取視頻流
AVStream *videoStream = m_formatContext->streams[m_videoStreamIndex];
// 建立解碼器上下文對象
m_videoCodecContext = [self createVideoEncderWithFormatContext:m_formatContext
stream:videoStream
videoStreamIndex:m_videoStreamIndex];
if (!m_videoCodecContext) {
log4cplus_error(kModuleName, "%s: create video codec failed",__func__);
return;
}
// 建立視頻幀
m_videoFrame = av_frame_alloc();
if (!m_videoFrame) {
log4cplus_error(kModuleName, "%s: alloc video frame failed",__func__);
avcodec_close(m_videoCodecContext);
}
}
複製代碼
- (AVCodecContext *)createVideoEncderWithFormatContext:(AVFormatContext *)formatContext stream:(AVStream *)stream videoStreamIndex:(int)videoStreamIndex {
AVCodecContext *codecContext = NULL;
AVCodec *codec = NULL;
// 指定解碼器名稱, 這裏使用蘋果VideoToolbox中的硬件解碼器
const char *codecName = av_hwdevice_get_type_name(AV_HWDEVICE_TYPE_VIDEOTOOLBOX);
// 將解碼器名稱轉爲對應的枚舉類型
enum AVHWDeviceType type = av_hwdevice_find_type_by_name(codecName);
if (type != AV_HWDEVICE_TYPE_VIDEOTOOLBOX) {
log4cplus_error(kModuleName, "%s: Not find hardware codec.",__func__);
return NULL;
}
// 根據解碼器枚舉類型找到解碼器
int ret = av_find_best_stream(formatContext, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
if (ret < 0) {
log4cplus_error(kModuleName, "av_find_best_stream faliture");
return NULL;
}
// 爲解碼器上下文對象分配內存
codecContext = avcodec_alloc_context3(codec);
if (!codecContext){
log4cplus_error(kModuleName, "avcodec_alloc_context3 faliture");
return NULL;
}
// 將視頻流中的參數填充到視頻解碼器中
ret = avcodec_parameters_to_context(codecContext, formatContext->streams[videoStreamIndex]->codecpar);
if (ret < 0){
log4cplus_error(kModuleName, "avcodec_parameters_to_context faliture");
return NULL;
}
// 建立硬件解碼器上下文
ret = InitHardwareDecoder(codecContext, type);
if (ret < 0){
log4cplus_error(kModuleName, "hw_decoder_init faliture");
return NULL;
}
// 初始化解碼器上下文對象
ret = avcodec_open2(codecContext, codec, NULL);
if (ret < 0) {
log4cplus_error(kModuleName, "avcodec_open2 faliture");
return NULL;
}
return codecContext;
}
#pragma mark - C Function
AVBufferRef *hw_device_ctx = NULL;
static int InitHardwareDecoder(AVCodecContext *ctx, const enum AVHWDeviceType type) {
int err = av_hwdevice_ctx_create(&hw_device_ctx, type, NULL, NULL, 0);
if (err < 0) {
log4cplus_error("XDXParseParse", "Failed to create specified HW device.\n");
return err;
}
ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
return err;
}
複製代碼
av_find_best_stream : 在文件中找到最佳流信息.ide
avcodec_parameters_to_context: 根據提供的解碼器參數中的值填充解碼器上下文函數
僅僅將解碼器中具備相應字段的任何已分配字段par被釋放並替換爲par中相應字段的副本。不涉及解碼器中沒有par中對應項的字段。post
int av_find_best_stream(AVFormatContext *ic,
enum FfmpegaVMediaType type,
int wanted_stream_nb,
int related_stream,
AVCodec **decoder_ret,
int flags);
複製代碼
AVFrame
做爲解碼後原始的音視頻數據的容器.AVFrame一般被分配一次而後屢次重複(例如,單個AVFrame以保持從解碼器接收的幀)。在這種狀況下,av_frame_unref()將釋放框架所持有的任何引用,並在再次重用以前將其重置爲其原始的清理狀態。ui
// Get video frame
m_videoFrame = av_frame_alloc();
if (!m_videoFrame) {
log4cplus_error(kModuleName, "%s: alloc video frame failed",__func__);
avcodec_close(m_videoCodecContext);
}
複製代碼
首先找到編碼數據流中第一個I幀, 而後調用avcodec_send_packet
將壓縮數據發送給解碼器.最後利用循環接收avcodec_receive_frame
解碼後的視頻數據.構造時間戳,並將解碼後的數據填充到CVPixelBufferRef
中並將其轉爲CMSampleBufferRef
.
- (void)startDecodeVideoDataWithAVPacket:(AVPacket)packet {
if (packet.flags == 1 && m_isFindIDR == NO) {
m_isFindIDR = YES;
m_base_time = m_videoFrame->pts;
}
if (m_isFindIDR == YES) {
[self startDecodeVideoDataWithAVPacket:packet
videoCodecContext:m_videoCodecContext
videoFrame:m_videoFrame
baseTime:m_base_time
videoStreamIndex:m_videoStreamIndex];
}
}
- (void)startDecodeVideoDataWithAVPacket:(AVPacket)packet videoCodecContext:(AVCodecContext *)videoCodecContext videoFrame:(AVFrame *)videoFrame baseTime:(int64_t)baseTime videoStreamIndex:(int)videoStreamIndex {
Float64 current_timestamp = [self getCurrentTimestamp];
AVStream *videoStream = m_formatContext->streams[videoStreamIndex];
int fps = DecodeGetAVStreamFPSTimeBase(videoStream);
avcodec_send_packet(videoCodecContext, &packet);
while (0 == avcodec_receive_frame(videoCodecContext, videoFrame))
{
CVPixelBufferRef pixelBuffer = (CVPixelBufferRef)videoFrame->data[3];
CMTime presentationTimeStamp = kCMTimeInvalid;
int64_t originPTS = videoFrame->pts;
int64_t newPTS = originPTS - baseTime;
presentationTimeStamp = CMTimeMakeWithSeconds(current_timestamp + newPTS * av_q2d(videoStream->time_base) , fps);
CMSampleBufferRef sampleBufferRef = [self convertCVImageBufferRefToCMSampleBufferRef:(CVPixelBufferRef)pixelBuffer
withPresentationTimeStamp:presentationTimeStamp];
if (sampleBufferRef) {
if ([self.delegate respondsToSelector:@selector(getDecodeVideoDataByFFmpeg:)]) {
[self.delegate getDecodeVideoDataByFFmpeg:sampleBufferRef];
}
CFRelease(sampleBufferRef);
}
}
}
複製代碼
avcodec_send_packet: 將壓縮視頻幀數據送給解碼器
avcodec_receive_frame()
讀取輸出的buffer. (一旦全部輸出讀取完畢,packet應該被從新發送,調用不會失敗)avcodec_receive_frame: 從解碼器中獲取解碼後的數據
釋放相關資源
- (void)stopDecoder {
[self freeAllResources];
}
- (void)freeAllResources {
if (m_videoCodecContext) {
avcodec_send_packet(m_videoCodecContext, NULL);
avcodec_flush_buffers(m_videoCodecContext);
if (m_videoCodecContext->hw_device_ctx) {
av_buffer_unref(&m_videoCodecContext->hw_device_ctx);
m_videoCodecContext->hw_device_ctx = NULL;
}
avcodec_close(m_videoCodecContext);
m_videoCodecContext = NULL;
}
if (m_videoFrame) {
av_free(m_videoFrame);
m_videoFrame = NULL;
}
}
複製代碼