[绍棠] kxmovie 源码的详解

kxmovie相信大部分人都很熟悉,一款非常棒的第三方开源流媒体播放器,当然你可能说ijkplay播放器更好,这里为了更好的研究ffmpeg解码播放的原理将对它进行剖析。

下载地址 点击打开链接  http://download.csdn.net/detail/itpeng523/8915993 

播放的原理:

一、打开流媒体文件

[objc]  view plain  copy
  1. + (id) movieViewControllerWithContentPath: (NSString *) path  
  2.                                parameters: (NSDictionary *) parameters  
  3. {  
  4.     //初始化音频  
  5.     id<KxAudioManager> audioManager = [KxAudioManager audioManager];  
  6.     [audioManager activateAudioSession];  
  7.     return [[KxMovieViewController alloc] initWithContentPath: path parameters: parameters];  
  8. }  
  9.   
  10. - (id) initWithContentPath: (NSString *) path  
  11.                 parameters: (NSDictionary *) parameters  
  12. {  
  13.     NSAssert(path.length > 0@"empty path");  
  14.       
  15.     self = [super initWithNibName:nil bundle:nil];  
  16.     if (self) {  
  17.           
  18.         _moviePosition = 0;  
  19. //        self.wantsFullScreenLayout = YES;  
  20.   
  21.         _parameters = parameters;  
  22.           
  23.         __weak KxMovieViewController *weakSelf = self;  
  24.           
  25.         KxMovieDecoder *decoder = [[KxMovieDecoder alloc] init];  
  26.         //设置解码器中断回调  
  27.         decoder.interruptCallback = ^BOOL(){  
  28.               
  29.             __strong KxMovieViewController *strongSelf = weakSelf;  
  30.             return strongSelf ? [strongSelf interruptDecoder] : YES;  
  31.         };  
  32.           
  33.         dispatch_async(dispatch_get_global_queue(00), ^{  
  34.       
  35.             NSError *error = nil;  
  36.             [decoder openFile:path error:&error];  
  37.                           
  38.             __strong KxMovieViewController *strongSelf = weakSelf;  
  39.             if (strongSelf) {  
  40.                   
  41.                 dispatch_sync(dispatch_get_main_queue(), ^{  
  42.                       
  43.                     [strongSelf setMovieDecoder:decoder withError:error];                      
  44.                 });  
  45.             }  
  46.         });  
  47.     }  
  48.     return self;  
  49. }  

我们可以看到这两个函数功能完成了音频播放器的初始化(这篇文章不解释音频播放器的做法,kxmovie用的AudioUnit来播放,后面单独介绍),初始化了KxMovieDecoder设置了中断函数的回调interruptCallback,最重要的openFile这里通过开启一个异步线程来执行此方法。下面具体看openFile:

[objc]  view plain  copy
  1. - (BOOL) openFile: (NSString *) path  
  2.             error: (NSError **) perror  
  3. {  
  4.     NSAssert(path, @"nil path");  
  5.     NSAssert(!_formatCtx, @"already open");  
  6.       
  7.     _isNetwork = isNetworkPath(path); //先判断是不是网络流  
  8.       
  9.     static BOOL needNetworkInit = YES;  
  10.     if (needNetworkInit && _isNetwork) {  
  11.           
  12.         needNetworkInit = NO;  
  13.         avformat_network_init();    //如果是网络流得先初始化  
  14.     }  
  15.       
  16.     _path = path;  
  17.     //打开文件  
  18.     kxMovieError errCode = [self openInput: path];  
  19.       
  20.     if (errCode == kxMovieErrorNone) {  
  21.           
  22.         kxMovieError videoErr = [self openVideoStream];//打开视频流  
  23.         kxMovieError audioErr = [self openAudioStream];//打开音频流  
  24.           
  25.         _subtitleStream = -1;  
  26.           
  27.         if (videoErr != kxMovieErrorNone &&  
  28.             audioErr != kxMovieErrorNone) {  
  29.            
  30.             errCode = videoErr; // both fails  
  31.               
  32.         } else {  
  33.               
  34.             _subtitleStreams = collectStreams(_formatCtx, AVMEDIA_TYPE_SUBTITLE);  
  35.         }  
  36.     }  
  37.       
  38.     if (errCode != kxMovieErrorNone) {  
  39.           
  40.         [self closeFile];  
  41.         NSString *errMsg = errorMessage(errCode);  
  42.         LoggerStream(0@"%@, %@", errMsg, path.lastPathComponent);  
  43.         if (perror)  
  44.             *perror = kxmovieError(errCode, errMsg);  
  45.         return NO;  
  46.     }  
  47.           
  48.     return YES;  
  49. }  
这个函数基本上完成了ffmpeg解码前的所有准备工作,接下来一个个看。

- (kxMovieError) openInput: (NSString *) path

[objc]  view plain  copy
  1. - (kxMovieError) openInput: (NSString *) path  
  2. {  
  3.     AVFormatContext *formatCtx = NULL;  
  4.     AVDictionary* options = NULL;  
  5.       
  6.     av_dict_set(&options, "rtsp_transport""tcp"0);      //把视频流的传输模式强制成tcp传输  
  7.     //设置加载时间  
  8.     av_dict_set(&options, "analyzeduration""2000000"0); //解析的最大时长这里的数字代表微妙 2000000/1000000 = 2s  
  9.     av_dict_set(&options, "probesize""122880"0);        //解析的容量上限为122880/1024M = 120M 可以自己设置不能太小否则会导致流的信息分析不完整  
  10.     if (_interruptCallback) {  
  11.           
  12.         formatCtx = avformat_alloc_context(); //初始化AVFormatContext 基本结构体 使用av_malloc分配了一块内存 主要用于处理封装格式(FLV/MKV/RMVB等)  
  13.         if (!formatCtx)  
  14.             return kxMovieErrorOpenFile;  
  15.         //处理中断函数 第一个参数函数指针 指向一个函数  
  16.         AVIOInterruptCB cb = {interrupt_callback, (__bridge voidvoid *)(self)};  
  17.         formatCtx->interrupt_callback = cb;  
  18.     }  
  19.     //打开文件 url_open,url_read  
  20.     if (avformat_open_input(&formatCtx, [path cStringUsingEncoding: NSUTF8StringEncoding], NULL, &options) < 0) {  
  21.           
  22.         if (formatCtx)  
  23.             avformat_free_context(formatCtx);  
  24.         return kxMovieErrorOpenFile;  
  25.     }  
  26.     //读取视音频数据相关的信息 parser find_decoder  avcodec_open2 实现了解码器的查找,解码器的打开,视音频帧的读取,视音频帧的解码  
  27.     if (avformat_find_stream_info(formatCtx, NULL) < 0) {  
  28.           
  29.         avformat_close_input(&formatCtx);  
  30.         return kxMovieErrorStreamInfoNotFound;  
  31.     }  
  32.   
  33.     av_dump_format(formatCtx, 0, [path.lastPathComponent cStringUsingEncoding: NSUTF8StringEncoding], false);  
  34.       
  35.     _formatCtx = formatCtx;  
  36.     return kxMovieErrorNone;  
  37. }  
rtsp_transport这里主要是为了把视频流的传输模式强制成tcp传输probesize是设置解析的容量上限,analyzeduration 解析的最大时长。可以根据源码来分析:

先看AVFormatContext结构体的初始化:

[objc]  view plain  copy
  1. AVFormatContext *avformat_alloc_context(void)  
  2. {  
  3.     AVFormatContext *ic;  
  4.     ic = av_malloc(sizeof(AVFormatContext));  
  5.     if (!ic) return ic;  
  6.     avformat_get_context_defaults(ic);  
  7.     ic->internal = av_mallocz(sizeof(*ic->internal));  
  8.      if (!ic->internal) {  
  9.          avformat_free_context(ic);  
  10.         return NULL;  
  11.     }  
  12.     return ic;  
  13. }  

使用av_malloc分配的一段空间,最基本的结构体,结构体里面的变量太多不一一列举,主要包括:AVStream **streams;//视频流结构体 unsignedint packet_size;//AVPacket数据的大小 unsignedint probesize;//容量大小 AVIOInterruptCB interrupt_callback;//中断回调 AVCodec *video_codec; AVCodec *audio_codec;这里只列出此代码中用到的。

接下来看打开媒体函数 avformat_open_input 的源码

[objc]  view plain  copy
  1. int avformat_open_input(AVFormatContext **ps, const charchar *filename,  
  2.                         AVInputFormat *fmt, AVDictionary **options)  
  3. {  
  4.     AVFormatContext *s = *ps;  
  5.     int ret = 0;  
  6.     AVDictionary *tmp = NULL;  
  7.     ID3v2ExtraMeta *id3v2_extra_meta = NULL;  
  8.   
  9.     if (!s && !(s = avformat_alloc_context()))  
  10.         return AVERROR(ENOMEM);  
  11.     if (!s->av_class) {  
  12.         av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");  
  13.         return AVERROR(EINVAL);  
  14.     }  
  15.     if (fmt)  
  16.         s->iformat = fmt;  
  17.   
  18.     if (options)  
  19.         av_dict_copy(&tmp, *options, 0);  
  20.   
  21.     if ((ret = av_opt_set_dict(s, &tmp)) < 0)  
  22.         goto fail;  
  23.   
  24.     if ((ret = init_input(s, filename, &tmp)) < 0)  
  25.         goto fail;  
  26.     s->probe_score = ret;  
  27.   
  28.     if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {  
  29.         av_log(s, AV_LOG_ERROR, "Format not on whitelist\n");  
  30.         ret = AVERROR(EINVAL);  
  31.         goto fail;  
  32.     }  
  33.   
  34.     avio_skip(s->pb, s->skip_initial_bytes);  
  35.   
  36.     /* Check filename in case an image number is expected. */  
  37.     if (s->iformat->flags & AVFMT_NEEDNUMBER) {  
  38.         if (!av_filename_number_test(filename)) {  
  39.             ret = AVERROR(EINVAL);  
  40.             goto fail;  
  41.         }  
  42.     }  
  43.   
  44.     s->duration = s->start_time = AV_NOPTS_VALUE;  
  45.     av_strlcpy(s->filename, filename ? filename : ""sizeof(s->filename));  
  46.   
  47.     /* Allocate private data. */  
  48.     if (s->iformat->priv_data_size > 0) {  
  49.         if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {  
  50.             ret = AVERROR(ENOMEM);  
  51.             goto fail;  
  52.         }  
  53.         if (s->iformat->priv_class) {  
  54.             *(const AVClass **) s->priv_data = s->iformat->priv_class;  
  55.             av_opt_set_defaults(s->priv_data);  
  56.             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)  
  57.                 goto fail;  
  58.         }  
  59.     }  
  60.   
  61.     /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */  
  62.     if (s->pb)  
  63.         ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, 0);  
  64.   
  65.     if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)  
  66.         if ((ret = s->iformat->read_header(s)) < 0)  
  67.             goto fail;  
  68.   
  69.     if (id3v2_extra_meta) {  
  70.         if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||  
  71.             !strcmp(s->iformat->name, "tta")) {  
  72.             if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)  
  73.                 goto fail;  
  74.         } else  
  75.             av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");  
  76.     }  
  77.     ff_id3v2_free_extra_meta(&id3v2_extra_meta);  
  78.   
  79.     if ((ret = avformat_queue_attached_pictures(s)) < 0)  
  80.         goto fail;  
  81.   
  82.     if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)  
  83.         s->data_offset = avio_tell(s->pb);  
  84.   
  85.     s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;  
  86.   
  87.     if (options) {  
  88.         av_dict_free(options);  
  89.         *options = tmp;  
  90.     }  
  91.     *ps = s;  
  92.     return 0;  
  93.   
  94. fail:  
  95.     ff_id3v2_free_extra_meta(&id3v2_extra_meta);  
  96.     av_dict_free(&tmp);  
  97.     if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))  
  98.         avio_close(s->pb);  
  99.     avformat_free_context(s);  
  100.     *ps = NULL;  
  101.     return ret;  
  102. }  
确实比较长,看几个重要的地方就行了,加深一下理解,主要通过init_input来完成初始化,其中通过read_header()读取多媒体的头文件,这些信息都存放在AVStream里面,有兴趣的可以再去研究ffmpeg的源码,后面就不直接贴源码了。

上面已经初始化了AVFormatContext基本结构体并且打开流媒体文件,接下来就得对流进行解码,这就牵涉到:解码器的查找、解码器的打开、视音频帧的读取、视音频帧的解码等,avformat_find_stream_info 就是用来完成这样的工作,所以它非常重要耗时也是比较长的,之所以前面设置analyzeduration、probesize在这里就起到作用了。简单看avformat_find_stream_info()函数里面的源码片段:

[objc]  view plain  copy
  1. int i, count, ret = 0, j;  
  2. int64_t read_size;  
  3. AVStream *st;  
  4. AVPacket pkt1, *pkt;  
  5. int64_t old_offset  = avio_tell(ic->pb);  
  6. // new streams might appear, no options for those  
  7. int orig_nb_streams = ic->nb_streams;  
  8. int flush_codecs;  
  9. int64_t max_analyze_duration = ic->max_analyze_duration2;  
  10. int64_t probesize = ic->probesize2;  
  11.   
  12.   
  13. if (!max_analyze_duration)  
  14. max_analyze_duration = ic->max_analyze_duration;  
  15. if (ic->probesize)  
  16. probesize = ic->probesize;  
  17. flush_codecs = probesize > 0;  
  18.   
  19.   
  20. av_opt_set(ic, "skip_clear""1", AV_OPT_SEARCH_CHILDREN);  
  21.   
  22.   
  23. if (!max_analyze_duration) {  
  24.     if (!strcmp(ic->iformat->name, "flv") && !(ic->ctx_flags & AVFMTCTX_NOHEADER)) {  
  25.         max_analyze_duration = 10*AV_TIME_BASE;  
  26.     } else  
  27.         max_analyze_duration = 5*AV_TIME_BASE;  
  28. }  

从这里可以看出  avformat_find_stream_info() 定义了AVStream(音视频流结构体st),AVPacket(音视频数据包结构体pkt,后面详细讲解),max_ analyze_duration( 解析的最大时长,前面的设置在这里起到了作用 ), probesize( 解析的容量上限也是在前面就设置了的 )。

其中流的解析器的初始化都是通过 st->parser = av_parser_init(st->codec->codec_id); 

codec = find_decoder(ic, st, st->codec->codec_id)函数用来实现解码器的查找,codec就是AVCodec的类型。avcodec_open2()函数用来打开解码器。

read_frame_internal()函数用来读取一帧完整的一帧压缩编码的数据,av_read_frame()函数的内部其实就是调用它来实现的。

try_decode_frame()函数就是用来解码压缩编码数据的。

总而言之avformat_find_stream_info()基本上已经实现了整个解码的流程,可想而知它的重要性。

文件打开已经完成接下面就进去音视频的流打开函数

视频流的打开:

[objc]  view plain  copy
  1. - (kxMovieError) openVideoStream  
  2. {  
  3.     kxMovieError errCode = kxMovieErrorStreamNotFound;  
  4.     _videoStream = -1;  
  5.     _artworkStream = -1;  
  6.     //收集视频流  
  7.     _videoStreams = collectStreams(_formatCtx, AVMEDIA_TYPE_VIDEO);  
  8.     for (NSNumber *n in _videoStreams) {  
  9.           
  10.         const NSUInteger iStream = n.integerValue;  
  11.   
  12.         if (0 == (_formatCtx->streams[iStream]->disposition & AV_DISPOSITION_ATTACHED_PIC)) {  
  13.           
  14.             errCode = [self openVideoStream: iStream];  
  15.             if (errCode == kxMovieErrorNone)  
  16.                 break;  
  17.               
  18.         } else {  
  19.               
  20.             _artworkStream = iStream;  
  21.         }  
  22.     }  
  23.       
  24.     return errCode;  
  25. }  
  26.   
  27. - (kxMovieError) openVideoStream: (NSInteger) videoStream  
  28. {      
  29.     // get a pointer to the codec context for the video stream 视频编解码器结构体  
  30.     AVCodecContext *codecCtx = _formatCtx->streams[videoStream]->codec;  
  31.       
  32.     // find the decoder for the video stream 找到解码器 我这里是H264  
  33.     AVCodec *codec = avcodec_find_decoder(codecCtx->codec_id);  
  34.     if (!codec)  
  35.         return kxMovieErrorCodecNotFound;  
  36.       
  37.     // inform the codec that we can handle truncated bitstreams -- i.e.,  
  38.     // bitstreams where frame boundaries can fall in the middle of packets  
  39.     //if(codec->capabilities & CODEC_CAP_TRUNCATED)  
  40.     //    _codecCtx->flags |= CODEC_FLAG_TRUNCATED;  
  41.       
  42.     // open codec 打开解码器  
  43.     if (avcodec_open2(codecCtx, codec, NULL) < 0)  
  44.         return kxMovieErrorOpenCodec;  
  45.           
  46.     _videoFrame = av_frame_alloc(); //初始化一个视频帧 分配一次 存储原始数据对于视频就是YUV或者RGB  
  47.   
  48.     if (!_videoFrame) {  
  49.         avcodec_close(codecCtx);  
  50.         return kxMovieErrorAllocateFrame;  
  51.     }  
  52.       
  53.     _videoStream = videoStream;  
  54.     _videoCodecCtx = codecCtx;  
  55.       
  56.     // determine fps  
  57.     //AVStream 存储每一个视频/音频流信息的结构体 st  
  58.     AVStream *st = _formatCtx->streams[_videoStream];  
  59.     //PTS*time_base=真正的时间  
  60.     avStreamFPSTimeBase(st, 0.04, &_fps, &_videoTimeBase);  
  61.       
  62.     LoggerVideo(1@"video codec size: %lu:%lu fps: %.3f tb: %f",  
  63.                 (unsigned long)self.frameWidth,  
  64.                 (unsigned long)self.frameHeight,  
  65.                 _fps,  
  66.                 _videoTimeBase);  
  67.       
  68.     LoggerVideo(1@"video start time %f", st->start_time * _videoTimeBase);  
  69.     LoggerVideo(1@"video disposition %d", st->disposition);  
  70.       
  71.     return kxMovieErrorNone;  
  72. }  
  73. static NSArray *collectStreams(AVFormatContext *formatCtx, enum AVMediaType codecType)  
  74. {  
  75.     NSMutableArray *ma = [NSMutableArray array];  
  76.      
  77.     for (NSInteger i = 0; i < formatCtx->nb_streams; ++i)  
  78.         if (codecType == formatCtx->streams[i]->codec->codec_type) //判断类型  
  79.             [ma addObject: [NSNumber numberWithInteger: i]];  
  80.     return [ma copy];  
  81. }  
打开视频流得先找到视频流,AVFormatContext结构体中nb_streams就存放着音频流的个数,正常一个流媒体文件里面只有一个视频流和一个音频流,这里通过collectStreams函数将视频流在streams的位置保存起来。接下来看打开视频流的过程:  
[objc]  view plain  copy
  1. <span style="font-size:18px;">- (kxMovieError) openVideoStream: (NSInteger) videoStream</span>  
代码里面都有注释主要得到了:  

_videoStream = videoStream;      //视频流在streams的位置

_videoCodecCtx = codecCtx;       //视频解码器结构体

_videoFrame av_frame_alloc(); //视频帧结构体

_videoTimeBase                           //基时

得到这些非常重要在后面的解码都用得着,是不是感觉跟前面avformat_find_stream_info()函数操作差不多 查找解码器打开解码器。
音频流的打开流程也差不多,这里不就贴代码,在讲音频播放的时候单独拿出来。在音视频流都打开了话就代表要到最后阶段了,下面就是解码显示部分,我看来看看kxmovie是怎么实现一般解码一边显示。

回到前面的代码:

[objc]  view plain  copy
  1. dispatch_sync(dispatch_get_main_queue(), ^{  
  2.                  
  3.       [strongSelf setMovieDecoder:decoder withError:error];                      
  4. });  
在setMovieDecoder()函数里面最主要的是设置_minBufferedDuration(最小缓存时长)和_maxBufferedDuration(最大缓存时长),这两个参数非常重要,现在直播这么火怎么保持直播流畅而又没有延时怎么处理好这些数据这是个关键,当然kxmovie这里的做法为了保证播放流畅给了一个最小缓存代码里面_minBufferedDuration = 2,_maxBufferedDuration = 4,界面上的代码不看了 直接跳到play函数:

[objc]  view plain  copy
  1. -(void) play  
  2. {  
  3.     if (self.playing)  
  4.         return;  
  5.       
  6.     if (!_decoder.validVideo &&  
  7.         !_decoder.validAudio) {  
  8.           
  9.         return;  
  10.     }  
  11.       
  12.     if (_interrupted)  
  13.         return;  
  14.   
  15.     self.playing = YES;  
  16.     _interrupted = NO;  
  17.     _disableUpdateHUD = NO;  
  18.     _tickCorrectionTime = 0;  
  19.     _tickCounter = 0;  
  20.   
  21. #ifdef DEBUG  
  22.     _debugStartTime = -1;  
  23. #endif  
  24.     //解码frame  
  25.     [self asyncDecodeFrames];  
  26.     [self updatePlayButton];  
  27.   
  28.     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC);  
  29.     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){  
  30.         [self tick];  
  31.     });  
  32.   
  33.     if (_decoder.validAudio)  
  34.         [self enableAudio:YES];  
  35.   
  36.     LoggerStream(1@"play movie");  
  37. }  
这里就得分两步走了 asyncDecodeFrames 开启一个异步线程去执行解码操作 另外一边在主线程执行播放的操作。先看
asyncDecodeFrames:

[objc]  view plain  copy
  1. - (void) asyncDecodeFrames  
  2. {  
  3.     if (self.decoding)  
  4.         return;  
  5.       
  6.     __weak KxMovieViewController *weakSelf = self;  
  7.     __weak KxMovieDecoder *weakDecoder = _decoder;  
  8.       
  9.     const CGFloat duration = _decoder.isNetwork ? .0f : 0.1f;  
  10.       
  11.     self.decoding = YES;  
  12.     dispatch_async(_dispatchQueue, ^{  
  13.           
  14.         {  
  15.             __strong KxMovieViewController *strongSelf = weakSelf;  
  16.             if (!strongSelf.playing)  
  17.                 return;  
  18.         }  
  19.           
  20.         BOOL good = YES;  
  21.         while (good) {  
  22.               
  23.             good = NO;  
  24.               
  25.             @autoreleasepool {  
  26.                   
  27.                 __strong KxMovieDecoder *decoder = weakDecoder;  
  28.                   
  29.                 if (decoder && (decoder.validVideo || decoder.validAudio)) {  
  30.                       
  31.                     NSArray *frames = [decoder decodeFrames:duration];  
  32.                     if (frames.count) {  
  33.                           
  34.                         __strong KxMovieViewController *strongSelf = weakSelf;  
  35.                         if (strongSelf)  
  36.                         {  
  37.                             good = [strongSelf addFrames:frames];  
  38.                         }  
  39.                     }  
  40.                 }  
  41.             }  
  42.         }  
  43.                   
  44.         {  
  45.             __strong KxMovieViewController *strongSelf = weakSelf;  
  46.             if (strongSelf) strongSelf.decoding = NO;  
  47.         }  
  48.     });  
  49. }  
代码很简单在这个线程里面开启一个whil(1)循环,使这个线程一直存活,一直在解码数据将解码玩的数据放addFrames进行处理。
[objc]  view plain  copy
  1. //解码帧  
  2. - (NSArray *) decodeFrames: (CGFloat) minDuration  
  3. {  
  4.     if (_videoStream == -1 &&  
  5.         _audioStream == -1)  
  6.         return nil;  
  7.   
  8.     NSMutableArray *result = [NSMutableArray array];  
  9.       
  10.     AVPacket packet;  
  11.       
  12.     CGFloat decodedDuration = 0;  
  13.       
  14.     BOOL finished = NO;  
  15.       
  16.     while (!finished) {  
  17.         //读取码流中的音频若干帧或者视频一帧  
  18.         if (av_read_frame(_formatCtx, &packet) < 0) {  
  19.             _isEOF = YES;  
  20.             break;  
  21.         }  
  22.         if (packet.stream_index ==_videoStream) {  
  23.              
  24.             int pktSize = packet.size;  
  25.               
  26.             while (pktSize > 0) {  
  27.                               
  28.                 int gotframe = 0;  
  29.                 //解码一帧视频  gotframe如果为0 代表没有帧解码 出错为负  
  30.                 int len = avcodec_decode_video2(_videoCodecCtx,  
  31.                                                 _videoFrame,  
  32.                                                 &gotframe,  
  33.                                                 &packet);  
  34.                 /** 
  35.                  *调用关键的函数 主要设置 picture 
  36.                  *avctx->codec->decode(avctx, picture, got_picture_ptr,&tmp); 
  37.                  * 
  38.                  */  
  39.                 if (len < 0) {  
  40.                     LoggerVideo(0@"decode video error, skip packet");  
  41.                     break;  
  42.                 }  
  43.                   
  44.                 if (gotframe) {  
  45.                       
  46.                     if (!_disableDeinterlacing &&  
  47.                         _videoFrame->interlaced_frame) {  
  48.   
  49.                         avpicture_deinterlace((AVPicture*)_videoFrame,  
  50.                                               (AVPicture*)_videoFrame,  
  51.                                               _videoCodecCtx->pix_fmt,  
  52.                                               _videoCodecCtx->width,  
  53.                                               _videoCodecCtx->height);  
  54.                     }  
  55.                       
  56.                     KxVideoFrame *frame = [self handleVideoFrame];  
  57.                     if (frame) {  
  58.                           
  59.                         [result addObject:frame];  
  60.                           
  61.                         _position = frame.position;  
  62.                         decodedDuration += frame.duration;  
  63.                         if (decodedDuration > minDuration)  
  64.                             finished = YES;  
  65.                     }  
  66.                 }  
  67.                                   
  68.                 if (0 == len)  
  69.                     break;  
  70.                   
  71.                 pktSize -= len;  
  72.             }  
  73.               
  74.         } else if (packet.stream_index == _audioStream) {  
  75.                           
  76.             int pktSize = packet.size;  
  77.               
  78.             while (pktSize > 0) {  
  79.                   
  80.                 int gotframe = 0;  
  81.                 int len = avcodec_decode_audio4(_audioCodecCtx,  
  82.                                                 _audioFrame,                                                  
  83.                                                 &gotframe,  
  84.                                                 &packet);  
  85.                   
  86.                 if (len < 0) {  
  87.                     LoggerAudio(0@"decode audio error, skip packet");  
  88.                     break;  
  89.                 }  
  90.                   
  91.                 if (gotframe) {  
  92.                       
  93.                     KxAudioFrame * frame = [self handleAudioFrame];  
  94.                     if (frame) {  
  95.                           
  96.                         [result addObject:frame];  
  97.                                                   
  98.                         if (_videoStream == -1) {  
  99.                               
  100.                             _position = frame.position;  
  101.                             decodedDuration += frame.duration;  
  102.                             if (decodedDuration > minDuration)  
  103.                                 finished = YES;  
  104.                         }  
  105.                     }  
  106.                 }  
  107.                   
  108.                 if (0 == len)  
  109.                     break;  
  110.                   
  111.                 pktSize -= len;  
  112.             }  
  113.               
  114.         } else if (packet.stream_index == _artworkStream) {  
  115.               
  116.             if (packet.size) {  
  117.   
  118.                 KxArtworkFrame *frame = [[KxArtworkFrame alloc] init];  
  119.                 frame.picture = [NSData dataWithBytes:packet.data length:packet.size];  
  120.                 [result addObject:frame];  
  121.             }  
  122.               
  123.         } else if (packet.stream_index == _subtitleStream) {  
  124.               
  125.             int pktSize = packet.size;  
  126.               
  127.             while (pktSize > 0) {  
  128.                   
  129.                 AVSubtitle subtitle;  
  130.                 int gotsubtitle = 0;  
  131.                 int len = avcodec_decode_subtitle2(_subtitleCodecCtx,  
  132.                                                   &subtitle,  
  133.                                                   &gotsubtitle,  
  134.                                                   &packet);  
  135.                   
  136.                 if (len < 0) {  
  137.                     LoggerStream(0@"decode subtitle error, skip packet");  
  138.                     break;  
  139.                 }  
  140.                   
  141.                 if (gotsubtitle) {  
  142.                       
  143.                     KxSubtitleFrame *frame = [self handleSubtitle: &subtitle];  
  144.                     if (frame) {  
  145.                         [result addObject:frame];  
  146.                     }  
  147.                     avsubtitle_free(&subtitle);  
  148.                 }  
  149.                   
  150.                 if (0 == len)  
  151.                     break;  
  152.                   
  153.                 pktSize -= len;  
  154.             }  
  155.         }  
  156.   
  157.         av_free_packet(&packet);  
  158.     }  
  159.   
  160.     return result;  
  161. }  
解码帧的函数,看得挺多的其实我们只需要看视频流和音频流就是了,一步一步来看。av_read_frame将读到的数据放到了一个AVPacket结构体中,如果是视频帧解码器是h264格式的话那AVPacket存的数据应该就是h264格式的数据,但是我们打印packet.data的数据并不是我们看到标准的nalu格式的数据也没有看到sps pps的一些信息,如果你们需要这些信息的话就可以这样做:

获取sps pps:

[objc]  view plain  copy
  1. /** 
  2.  *        获取AVPacket中的h264中的 sps与pps<span style="font-family: Arial, Helvetica, sans-serif;">数据</span> 
  3.  * 
  4.  *        unsigned char *dummy=NULL;   //输入的指针 
  5.  *        int dummy_len; 
  6.  *        AVBitStreamFilterContext* bsfc =  av_bitstream_filter_init("h264_mp4toannexb"); 
  7.  *        av_bitstream_filter_filter(bsfc, _videoCodecCtx, NULL, &dummy, &dummy_len, NULL, 0, 0); 
  8.  *        av_bitstream_filter_close(bsfc); 
  9.  *        free(dummy); 
  10.  *        NSLog(@"_formatCtx extradata = %@, packet ===== %@",[NSData dataWithBytes:_videoCodecCtx->extradata length:_videoCodecCtx->extradata_size],[NSData dataWithBytes:packet.data length:packet.size]); 
  11.  * 
  12.  * 
  13.  */  
获得标准的nalu格式数据:

AVPacket中的数据起始处没有分隔符(0x00000001), 也不是0x650x670x680x41等字节,所以可以AVPacket肯定这不是标准的nalu。其实,AVPacket4个字表示的是nalu的长度,从第5个字节开始才是nalu的数据。所以直接将AVPacket4个字节替换为0x00000001即可得到标准的nalu数据。

AVPacket就介绍到这里,下面看avcodec_decode_video2解码函数,将解码出来的数据放到AVFrame中,格式我这里解码出来的是YUV格式的数据。

下面来看:

[objc]  view plain  copy
  1. - (KxVideoFrame *) handleVideoFrame  
  2. {  
  3.     if (!_videoFrame->data[0])  
  4.         return nil;  
  5.       
  6.     KxVideoFrame *frame;  
  7.       
  8.     if (_videoFrameFormat == KxVideoFrameFormatYUV) {  
  9.               
  10.         KxVideoFrameYUV * yuvFrame = [[KxVideoFrameYUV alloc] init];  
  11.         //将YUV分离出来w*h*3/2 Byte的数据  
  12.         //Y 亮度  w*h Byte存储Y 拷贝一帧图片的数据  
  13.         yuvFrame.luma = copyFrameData(_videoFrame->data[0],  
  14.                                       _videoFrame->linesize[0],  
  15.                                       _videoCodecCtx->width,  
  16.                                       _videoCodecCtx->height);  
  17.           
  18.         //U 色度 w*h*1/4 Byte存储U  
  19.         yuvFrame.chromaB = copyFrameData(_videoFrame->data[1],  
  20.                                          _videoFrame->linesize[1],  
  21.                                          _videoCodecCtx->width / 2,  
  22.                                          _videoCodecCtx->height / 2);  
  23.           
  24.         //V 浓度 w*h*1/4 Byte存储V  
  25.         yuvFrame.chromaR = copyFrameData(_videoFrame->data[2],  
  26.                                          _videoFrame->linesize[2],  
  27.                                          _videoCodecCtx->width / 2,  
  28.                                          _videoCodecCtx->height / 2);  
  29.           
  30.         frame = yuvFrame;  
  31.       
  32.     } else {  
  33.       
  34.         if (!_swsContext &&  
  35.             ![self setupScaler]) {  
  36.               
  37.             LoggerVideo(0@"fail setup video scaler");  
  38.             return nil;  
  39.         }  
  40.           
  41.         sws_scale(_swsContext,  
  42.                   (const uint8_t **)_videoFrame->data,  
  43.                   _videoFrame->linesize,  
  44.                   0,  
  45.                   _videoCodecCtx->height,  
  46.                   _picture.data,  
  47.                   _picture.linesize);  
  48.           
  49.           
  50.         KxVideoFrameRGB *rgbFrame = [[KxVideoFrameRGB alloc] init];  
  51.           
  52.         rgbFrame.linesize = _picture.linesize[0];  
  53.         rgbFrame.rgb = [NSData dataWithBytes:_picture.data[0]  
  54.                                     length:rgbFrame.linesize * _videoCodecCtx->height];  
  55.         frame = rgbFrame;  
  56.     }      
  57.       
  58.     frame.width = _videoCodecCtx->width;  
  59.     frame.height = _videoCodecCtx->height;  
  60.     //_videoTimeBase = 0.001 当前的时间 = pts*_videoTimeBase  
  61.     frame.position = av_frame_get_best_effort_timestamp(_videoFrame) * _videoTimeBase;  
  62.   
  63.     const int64_t frameDuration = av_frame_get_pkt_duration(_videoFrame);  
  64.     if (frameDuration) {  
  65.           
  66.         frame.duration = frameDuration * _videoTimeBase;  
  67.         frame.duration += _videoFrame->repeat_pict * _videoTimeBase * 0.5;  
  68.           
  69.     } else {  
  70.           
  71.         // sometimes, ffmpeg unable to determine a frame duration  
  72.         // as example yuvj420p stream from web camera  
  73.         frame.duration = 1.0 / _fps;  
  74.     }  
  75. #if 0  
  76.     LoggerVideo(2@"VFD: %.4f %.4f | %lld ",  
  77.                 frame.position,  
  78.                 frame.duration,  
  79.                 av_frame_get_pkt_pos(_videoFrame));  
  80. #endif  
  81.       
  82.     return frame;  
  83. }  
这个函数首先把YUV格式的数据分离开来分别放到luma、chromaB、chromaR中。

frame.position =av_frame_get_best_effort_timestamp(_videoFrame) *_videoTimeBase;这个参数非常重要得到当前显示的时间在播放器中用在播放时间的显示。

frame.duration =1.0 / _fps; //得到了当前帧的需要显示的时长 比如我的推流端设置的帧率是25帧那么一帧需要显示的时长就是0.04s这个参数也很重要。

解码完返回数据:

[objc]  view plain  copy
  1. - (BOOL) addFrames: (NSArray *)frames  
  2. {  
  3.     if (_decoder.validVideo) {  
  4.           
  5.         @synchronized(_videoFrames) {  
  6.               
  7.             for (KxMovieFrame *frame in frames)  
  8.                 if (frame.type == KxMovieFrameTypeVideo) {  
  9.                     [_videoFrames addObject:frame];  
  10.                     _bufferedDuration += frame.duration;  
  11.                 }  
  12.         }  
  13.     }  
  14.       
  15.     if (_decoder.validAudio) {  
  16.           
  17.         @synchronized(_audioFrames) {  
  18.               
  19.             for (KxMovieFrame *frame in frames)  
  20.                 if (frame.type == KxMovieFrameTypeAudio) {  
  21.                     [_audioFrames addObject:frame];  
  22.                     if (!_decoder.validVideo)  
  23.                         _bufferedDuration += frame.duration;  
  24.                 }  
  25.         }  
  26.           
  27.         if (!_decoder.validVideo) {  
  28.               
  29.             for (KxMovieFrame *frame in frames)  
  30.                 if (frame.type == KxMovieFrameTypeArtwork)  
  31.                     self.artworkFrame = (KxArtworkFrame *)frame;  
  32.         }  
  33.     }  
  34.       
  35.     if (_decoder.validSubtitles) {  
  36.           
  37.         @synchronized(_subtitles) {  
  38.               
  39.             for (KxMovieFrame *frame in frames)  
  40.                 if (frame.type == KxMovieFrameTypeSubtitle) {  
  41.                     [_subtitles addObject:frame];  
  42.                 }  
  43.         }  
  44.     }  
  45.       //最大缓存  
  46.     return self.playing && _bufferedDuration < _maxBufferedDuration;  
  47. }  
这个函数主要对_bufferedDuration(缓存时长)进行累加,以及对数据的保存都存放一个数组里面,最后面判断当前的缓存有没有超过最大的缓存。这样一个视频帧的解码以及的采集就完成,接着回去看主线程的显示。

第一次定时(tick):

[objc]  view plain  copy
  1. dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC);  
  2. dispatch_after(popTime, dispatch_get_main_queue(), ^(void){  
  3.     [self tick];  
  4. });  
这个函数也就是延时操作,为什么这样做其实就是为了做开始加载的缓存,可以分析一下这里是0.1s后再去执行 tick函数,在此之间已经解码几十帧数据了。接下来看tick函数:

[objc]  view plain  copy
  1. - (void) tick  
  2. {  
  3.     //缓存的时长  
  4.     if (_buffered && ((_bufferedDuration > _minBufferedDuration) || _decoder.isEOF)) {  
  5.           
  6.         _tickCorrectionTime = 0;  
  7.         _buffered = NO;  
  8.         [_activityIndicatorView stopAnimating];          
  9.     }  
  10.       
  11.     CGFloat interval = 0;  
  12.     if (!_buffered)  
  13.         interval = [self presentFrame];  //显示一帧  
  14.       
  15.     if (self.playing) {  
  16.           
  17.         //还有可显示的音视频帧  
  18.         const NSUInteger leftFrames =  
  19.         (_decoder.validVideo ? _videoFrames.count : 0) +  
  20.         (_decoder.validAudio ? _audioFrames.count : 0);  
  21.           
  22.         if (0 == leftFrames)  //如果没有要显示的数据了  
  23.         {  
  24.             if (_decoder.isEOF) {  
  25.                   
  26.                 [self pause];  
  27.                 [self updateHUD];  
  28.                 return;  
  29.             }  
  30.               
  31.             if (_minBufferedDuration > 0 && !_buffered)//确认缓存里面是否还有数据  
  32.             {  
  33.                                   
  34.                 _buffered = YES;  
  35.                 [_activityIndicatorView startAnimating];  //开始转  
  36.             }  
  37.         }  
  38.           
  39.         if (!leftFrames ||  
  40.             !(_bufferedDuration > _minBufferedDuration))  
  41.         {  
  42.               
  43.             [self asyncDecodeFrames];  
  44.         }  
  45.           
  46.         const NSTimeInterval correction = [self tickCorrection];  
  47.         const NSTimeInterval time = MAX(interval + correction, 0.01);  
  48.         dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, time * NSEC_PER_SEC);  
  49.         dispatch_after(popTime, dispatch_get_main_queue(), ^(void){  
  50.             [self tick];  
  51.         });  
  52.     }  
  53.       
  54.     if ((_tickCounter++ % 3) == 0) {  
  55.         [self updateHUD];  
  56.     }  
  57. }  
  58.   
  59. - (CGFloat) tickCorrection  
  60. {  
  61.     if (_buffered)  
  62.         return 0;  
  63.       
  64.     const NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];  
  65.       
  66.     if (!_tickCorrectionTime) {  
  67.           
  68.         _tickCorrectionTime = now;  
  69.         _tickCorrectionPosition = _moviePosition; //播放的位置 就是现在播的的时间  
  70.         return 0;  
  71.     }  
  72.       
  73.     NSTimeInterval dPosition = _moviePosition - _tickCorrectionPosition;  
  74.     NSTimeInterval dTime = now - _tickCorrectionTime;  
  75.     NSTimeInterval correction = dPosition - dTime;  
  76.     if (correction > 1.f || correction < -1.f) {  
  77.           
  78.         LoggerStream(1@"tick correction reset %.2f", correction);  
  79.         correction = 0;  
  80.         _tickCorrectionTime = 0;  
  81.     }  
  82.       
  83.     return correction;  
  84. }  
  85.   
  86. - (CGFloat) presentFrame  
  87. {  
  88.     CGFloat interval = 0;  
  89.       
  90.     if (_decoder.validVideo) {  
  91.           
  92.         KxVideoFrame *frame;  
  93.           
  94.         @synchronized(_videoFrames) {  
  95.               
  96.             if (_videoFrames.count > 0) {  
  97.                   
  98.                 frame = _videoFrames[0];  
  99.                 [_videoFrames removeObjectAtIndex:0];  
  100.                 _bufferedDuration -= frame.duration;  
  101.             }  
  102.         }  
  103.           
  104.         if (frame)  
  105.             interval = [self presentVideoFrame:frame];  
  106.           
  107.     } else if (_decoder.validAudio) {  
  108.   
  109.         //interval = _bufferedDuration * 0.5;  
  110.                   
  111.         if (self.artworkFrame) {  
  112.               
  113.             _imageView.image = [self.artworkFrame asImage];  
  114.             self.artworkFrame = nil;  
  115.         }  
  116.     }  
  117.   
  118.     if (_decoder.validSubtitles)  
  119.         [self presentSubtitles];  
  120.       
  121. #ifdef DEBUG  
  122.     if (self.playing && _debugStartTime < 0)  
  123.         _debugStartTime = [NSDate timeIntervalSinceReferenceDate] - _moviePosition;  
  124. #endif  
  125.   
  126.     return interval;  
  127. }  
tick函数其实就相当于一个被一个定时器循环调用一样隔多少秒调用一次隔多少秒调用一次,调用一次显示一帧数据,下面来看具体的操作:

首先

if (_buffered && ((_bufferedDuration >_minBufferedDuration) || _decoder.isEOF))

这里有个判断语句 _buffered表示是否需要缓存,如果数组里面有数据当然不需要缓存为NO否则为

YES。_bufferedDuration > _minBufferedDuration判断是否大于最小的缓存这里是2s。分析一下,tick()是在开始解码后0.1s才开始调用_bufferedDuration是进行帧的duration进行累加的,一帧是0.04s要大于2s的缓存肯定至少要解码50帧才可以显示。但是_buffered初始化设置为No,所以第一次缓存帧数是定时0.1的数量。

    if (!_buffered)

        interval = [selfpresentFrame];  //显示一帧

下面看一个网络不好的操作

[objc]  view plain  copy
  1. if (0 == leftFrames)  //如果没有要显示的数据了  
  2. {  
  3.     if (_decoder.isEOF) {  
  4.           
  5.         [self pause];  
  6.         [self updateHUD];  
  7.         return;  
  8.     }  
  9.       
  10.     if (_minBufferedDuration > 0 && !_buffered)//确认缓存里面是否还有数据  
  11.     {  
  12.                           
  13.         _buffered = YES;  
  14.         [_activityIndicatorView startAnimating];  //开始转  
  15.     }  
  16. }  
这里也很好理解,当显示数据的数组里面没有数据了,自然就要等待,进行缓存,此时_minBufferedDuration肯定为0了,因为每显示一帧数据都要减去这一帧的duration,等数据都显示完了自然也就为0,将_buffered置为YES。这时不会调用presentFrame而且必须要等到_bufferedDuration > _minBufferedDuration才开始显示。后面的OpenGLES显示就不写了,到此kxmovie的解码显示过程基本上也写清楚了。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值