FFmpeg學習之開發(fā)Mac播放器(二):YUV數(shù)據(jù)轉為RGB數(shù)據(jù)并渲染

  • 解碼出的YUV數(shù)據(jù)要轉成RGB數(shù)據(jù)然后顯示,我使用AVFilter進行轉換而不是sws_scale
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    videoIndex = NSNotFound;
    [self initDecoder];  //初始化解碼器
    [self initFilters];  //初始化過濾器

    self.view.frame = NSRectFromCGRect(CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, pCodecCtx->width, pCodecCtx->height));

    timer = [NSTimer timerWithTimeInterval:1/fps repeats:YES block:^(NSTimer * _Nonnull timer) { //根據(jù)視頻的fps解碼渲染視頻
        [self decodeVideo];  //解碼視頻并渲染
        [self.view setNeedsLayout:YES];  //刷新界面防止畫面撕裂
    }];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSEventTrackingRunLoopMode]; //在改變尺寸時保證計時器能調用
}
初始化解碼器
- (void)initDecoder {
    //av_register_all(); FFmpeg 4.0廢棄

    NSString * videoPath = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"];
    pFormatCtx = avformat_alloc_context();

    if ((avformat_open_input(&pFormatCtx, videoPath.UTF8String, NULL, NULL)) != 0) {
        NSLog(@"Could not open input stream");
        return;
    }

    if ((avformat_find_stream_info(pFormatCtx, NULL)) < 0) {
        NSLog(@"Could not find stream information");
        return;
    }

    for (NSInteger i = 0; i < pFormatCtx->nb_streams; i++) {
        if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoIndex = i;  //視頻流的索引
            videoDuration = pFormatCtx->streams[i]->duration * av_q2d(pFormatCtx->streams[i]->time_base); //計算視頻時長
            _totalTimeLabel.stringValue = [NSString stringWithFormat:@"%.2ld:%.2ld", videoDuration/60, videoDuration%60];
            if (pFormatCtx->streams[i]->avg_frame_rate.den && pFormatCtx->streams[i]->avg_frame_rate.num) {
                fps = av_q2d(pFormatCtx->streams[i]->avg_frame_rate);  //計算視頻fps
            } else {
                fps = 30;
            }
            break;
        }
    }

    if (videoIndex == NSNotFound) {
        NSLog(@"Did not find a video stream");
        return;
    }

    // FFmpeg 3.1 以上AVStream::codec被替換為AVStream::codecpar
    pCodec = avcodec_find_decoder(pFormatCtx->streams[videoIndex]->codecpar->codec_id);
    pCodecCtx = avcodec_alloc_context3(pCodec);
    avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[videoIndex]->codecpar);

    if (pCodec == NULL) {
        NSLog(@"Could not open codec");
        return;
    }

    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
        NSLog(@"Could not open codec");
        return;
    }

    av_dump_format(pFormatCtx, 0, videoPath.UTF8String, 0);
}
初始化過濾器
- (void)initFilters {

//    avfilter_register_all();  //FFmpeg 4.0廢棄

    char args[512];

    AVFilterInOut * inputs = avfilter_inout_alloc();
    AVFilterInOut * outputs = avfilter_inout_alloc();
    AVFilterGraph * filterGraph = avfilter_graph_alloc();

    const AVFilter * buffer = avfilter_get_by_name("buffer");
    const AVFilter * bufferSink = avfilter_get_by_name("buffersink");
    if (!buffer || !bufferSink) {
        NSLog(@"filter not found");
        return;
    }
    AVRational time_base = pFormatCtx->streams[videoIndex]->time_base;
    //視頻的描述字符串,這些屬性都是必須的否則會創(chuàng)建失敗
    snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,
             time_base.num, time_base.den,pCodecCtx->sample_aspect_ratio.num,pCodecCtx->sample_aspect_ratio.den);
    NSInteger ret = avfilter_graph_create_filter(&buffer_ctx, buffer, "in", args, NULL, filterGraph);
    if (ret < 0) {
        NSLog(@"can not create buffer source");
        return;
    }
    ret = avfilter_graph_create_filter(&bufferSink_ctx, bufferSink, "out", NULL, NULL, filterGraph);
    if (ret < 0) {
        NSLog(@"can not create buffer sink");
        return;
    }
    enum AVPixelFormat format[] = {AV_PIX_FMT_RGB24};  //想要轉換的格式
    ret = av_opt_set_bin(bufferSink_ctx, "pix_fmts", (uint8_t *)&format, sizeof(AV_PIX_FMT_RGB24), AV_OPT_SEARCH_CHILDREN);
    if (ret < 0) {
        NSLog(@"set bin error");
        return;
    }

    outputs->name = av_strdup("in");
    outputs->filter_ctx = buffer_ctx;
    outputs->pad_idx = 0;
    outputs->next = NULL;

    inputs->name = av_strdup("out");
    inputs->filter_ctx = bufferSink_ctx;
    inputs->pad_idx = 0;
    inputs->next = NULL;

    ret = avfilter_graph_parse_ptr(filterGraph, "null", &inputs, &outputs, NULL);  //只轉換格式filter名稱輸入null
    if (ret < 0) {
        NSLog(@"parse error");
        return;
    }

    ret = avfilter_graph_config(filterGraph, NULL);
    if (ret < 0) {
        NSLog(@"config error");
        return;
    }

    avfilter_inout_free(&inputs);
    avfilter_inout_free(&outputs);
}
解碼并渲染視頻
- (void)decodeVideo {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  //在全局隊列中解碼
        AVPacket * packet = av_packet_alloc();
        if (av_read_frame(self->pFormatCtx, packet) >= 0) {
            if (packet->stream_index == self->videoIndex) {  //解碼視頻流
                //FFmpeg 3.0之后avcodec_send_packet和avcodec_receive_frame成對出現(xiàn)用于解碼,包括音頻和視頻的解碼酗昼,avcodec_decode_video2和avcodec_decode_audio4被廢棄
                NSInteger ret = avcodec_send_packet(self->pCodecCtx, packet);
                if (ret < 0) {
                    NSLog(@"send packet error");
                    av_packet_free(&packet);
                    return;
                }
                AVFrame * frame = av_frame_alloc();
                ret = avcodec_receive_frame(self->pCodecCtx, frame);
                if (ret < 0) {
                    NSLog(@"receive frame error");
                    av_frame_free(&frame);
                    return;
                }
                //把解碼出的frame傳入filter中進行格式轉換
                ret = av_buffersrc_add_frame_flags(self->buffer_ctx, frame, 0);
                if (ret < 0) {
                    NSLog(@"add frame error");
                    return;
                }
                //將轉換好的rgbFrame取出來
                AVFrame * rgbFrame = av_frame_alloc();
                ret = av_buffersink_get_frame(self->bufferSink_ctx, rgbFrame);
                if (ret < 0) {
                    NSLog(@"get frame error");
                    return;
                }
                /*
                 frame中data存放解碼出的yuv數(shù)據(jù),data[0]中是y數(shù)據(jù),data[1]中是u數(shù)據(jù)博助,data[2]中是v數(shù)據(jù),linesize對應的數(shù)據(jù)長度
                 rgb數(shù)據(jù)全部都存放在frame的data[0]中
                 */
                float time = packet->pts * av_q2d(self->pFormatCtx->streams[self->videoIndex]->time_base);  //計算當前幀時間
                av_packet_free(&packet);
                av_frame_free(&frame);
                //將frame中的RGB數(shù)據(jù)轉成NSImage顯示
                CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, rgbFrame->data[0], rgbFrame->linesize[0] * self->pCodecCtx->height, kCFAllocatorNull);
                if (CFDataGetLength(data) != 0) {
                    CGDataProviderRef provider = CGDataProviderCreateWithCFData(data);
                    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
                    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
                    CGImageRef cgImage = CGImageCreate(self->pCodecCtx->width, self->pCodecCtx->height, 8, 24, rgbFrame->linesize[0], colorSpace, bitmapInfo, provider, NULL, YES, kCGRenderingIntentDefault);
                    NSImage * image = [[NSImage alloc] initWithCGImage:cgImage size:NSSizeFromCGSize(CGSizeMake(self->pCodecCtx->width, self->pCodecCtx->height))];
                    CGImageRelease(cgImage);
                    CGDataProviderRelease(provider);
                    CGColorSpaceRelease(colorSpace);
                    av_frame_free(&rgbFrame);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.label.stringValue = [NSString stringWithFormat:@"%.2d:%.2d", (int)time/60, (int)time%60];
                        self.imageView.image = image;
                        self.slider.floatValue = time / (float)self->videoDuration;
                    });
                }
            }
        } else {
            avcodec_free_context(&self->pCodecCtx);
            avformat_close_input(&self->pFormatCtx);
            avformat_free_context(self->pFormatCtx);
            [self->timer invalidate];
        }
    });
}
播放畫面.png

雖然能播放視頻但是有一個問題痹愚,根據(jù)視頻的FPS調用定時器解碼顯示視頻幀率并不能達到視頻的幀率富岳,因為解碼,轉換格式拯腮,合成圖片這些操作費時窖式,而且CPU占用率也很高,這些問題后面會解決动壤。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末萝喘,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子琼懊,更是在濱河造成了極大的恐慌阁簸,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件哼丈,死亡現(xiàn)場離奇詭異启妹,居然都是意外死亡,警方通過查閱死者的電腦和手機醉旦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門饶米,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人车胡,你說我怎么就攤上這事檬输。” “怎么了匈棘?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵褪猛,是天一觀的道長。 經(jīng)常有香客問我羹饰,道長伊滋,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任队秩,我火速辦了婚禮笑旺,結果婚禮上,老公的妹妹穿的比我還像新娘馍资。我一直安慰自己筒主,他們只是感情好,可當我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著乌妙,像睡著了一般使兔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上藤韵,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天虐沥,我揣著相機與錄音,去河邊找鬼泽艘。 笑死欲险,一個胖子當著我的面吹牛,可吹牛的內容都是我干的匹涮。 我是一名探鬼主播天试,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼然低!你這毒婦竟也來了喜每?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤雳攘,失蹤者是張志新(化名)和其女友劉穎带兜,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體来农,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡鞋真,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了沃于。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片涩咖。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖繁莹,靈堂內的尸體忽然破棺而出檩互,到底是詐尸還是另有隱情,我是刑警寧澤咨演,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布闸昨,位于F島的核電站,受9級特大地震影響薄风,放射性物質發(fā)生泄漏饵较。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一遭赂、第九天 我趴在偏房一處隱蔽的房頂上張望循诉。 院中可真熱鬧,春花似錦撇他、人聲如沸茄猫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽划纽。三九已至脆侮,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間勇劣,已是汗流浹背靖避。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留芭毙,地道東北人筋蓖。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓卸耘,卻偏偏與公主長得像退敦,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蚣抗,可洞房花燭夜當晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內容

  • 教程一:視頻截圖(Tutorial 01: Making Screencaps) 首先我們需要了解視頻文件的一些基...
    90后的思維閱讀 4,710評論 0 3
  • 1侈百、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明先生_X自主閱讀 15,988評論 3 119
  • FFmpeg 介紹 FFmpeg是一套可以用來記錄、轉換數(shù)字音頻翰铡、視頻钝域,并能將其轉化為流的開源計算機程序。采用LG...
    Y了個J閱讀 11,309評論 0 28
  • 很多時候你一個人習慣了锭魔,就無法給與囑托例证,你習慣了如風般不結伴穿梭,影子都沒留片刻迷捧,很多時候你一個人常常是织咧,只考慮一...
    小虎仔啦啦啦閱讀 349評論 0 0
  • 反邪防邪 人人有責 (對口詞) 甲:全黨動員 全民參與 乙:鏟除邪教 構建...
    張世林zsl閱讀 542評論 0 1