FFmpeg學(xué)習(xí)之開(kāi)發(fā)Mac播放器(五):使用FFmpeg硬解碼視頻

MacOS和iOS支持VideoToolbox進(jìn)行硬件解碼H264編碼的視頻膝舅,F(xiàn)Fmpeg也支持VideoToolbox拥知,參考官方的example實(shí)現(xiàn)FFmpeg硬解視頻山卦。

    enum AVHWDeviceType type = av_hwdevice_find_type_by_name("videotoolbox"); //MacOS和iOS可以固定寫(xiě)videotoolbox
    if (avformat_open_input(&input_ctx, [inputString UTF8String], NULL, NULL) != 0) {
        fprintf(stderr, "Can not open input file '%s'\n", [inputString UTF8String]);
        return -1;
    }
    if (avformat_find_stream_info(input_ctx, NULL) < 0) {
        fprintf(stderr, "Can not find stream information\n");
        return -1;
    }
    ret = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0);
    if (ret < 0) {
        fprintf(stderr, "Can not find a video stream in the input file\n");
        return -1;
    }
    video_stream = ret;
    for (i = 0; ; i++) {
        const AVCodecHWConfig * config = avcodec_get_hw_config(decoder, i);
        if (!config) {
            fprintf(stderr, "Decoder %s does not support device type %s.\n", decoder->name, av_hwdevice_get_type_name(type));
            return -1;
        }
        if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == type) {
            hw_pix_fmt = config->pix_fmt; //獲取硬件支持的圖像格式
            break;
        }
    }
    if (!(decoder_ctx = avcodec_alloc_context3(decoder))) {
        return AVERROR(ENOMEM);
    }
    video = input_ctx->streams[video_stream];
    if (avcodec_parameters_to_context(decoder_ctx, video->codecpar) < 0) {
        return -1;
    }
    decoder_ctx->get_format = get_hw_format;   //將硬件支持的圖像格式傳給解碼器的方法
    if (hw_decoder_init(decoder_ctx, type) < 0) {
        return -1;
    }
    if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0) {
        fprintf(stderr, "Failed to open codec for stream #%u\n", video_stream);
        return -1;
    }
    output_file = fopen([outputString UTF8String], "wb");
    while (ret >= 0) {
        if ((ret = av_read_frame(input_ctx, &packet)) < 0) {
            break;
        }
        if (video_stream == packet.stream_index) {
            ret = decode_write(decoder_ctx, &packet);
        }
        av_packet_unref(&packet);
    }
    packet.data = NULL;
    packet.size = 0;
    ret = decode_write(decoder_ctx, &packet);
    av_packet_unref(&packet);

    if (output_file) {
        fclose(output_file);
    }
    avcodec_free_context(&decoder_ctx);
    avformat_close_input(&input_ctx);
    av_buffer_unref(&hw_device_ctx);
    return 0;
static int hw_decoder_init(AVCodecContext * ctx, const enum AVHWDeviceType type) {
    int err = 0;
    if ((err = av_hwdevice_ctx_create(&hw_device_ctx, type, NULL, NULL, 0)) < 0) {
        fprintf(stderr, "Failed to create specified HW device.\n");
        return err;
    }
    ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx); //創(chuàng)建hw_device_ctx傳給解碼器上下文,必須在avcodec_open2之前并且之后不能修改
    return err;
}

static enum AVPixelFormat get_hw_format(AVCodecContext * ctx, const enum AVPixelFormat * pix_fmts) {
    const enum AVPixelFormat * p;
    for (p = pix_fmts; *p != -1; p++) {
        if (*p == hw_pix_fmt) {
            return *p;
        }
    }
    fprintf(stderr, "Failed to get HW surface format.\n");
    return AV_PIX_FMT_NONE;
}
static int decode_write(AVCodecContext * avctx, AVPacket * packet) {  //解碼的方法
    AVFrame * frame = NULL, * sw_frame = NULL;
    AVFrame * tmp_frame = NULL;
    uint8_t * buffer = NULL;
    int size;
    int ret = 0;

    ret = avcodec_send_packet(avctx, packet);
    if (ret < 0) {
        fprintf(stderr, "Error during decoding\n");
        return ret;
    }
    while (1) {
        if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc())) {
            fprintf(stderr, "Can not alloc frame\n");
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        ret = avcodec_receive_frame(avctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
            av_frame_free(&frame);
            av_frame_free(&sw_frame);
            return 0;
        } else if (ret < 0) {
            fprintf(stderr, "Error while decoding\n");
            goto fail;
        }
        if (frame->format == hw_pix_fmt) {
            if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) { //從GPU取出解碼的數(shù)據(jù)
                fprintf(stderr, "Error transferring the data to system memory\n");
                goto fail;
            }
            tmp_frame = sw_frame;
        } else {
            tmp_frame = frame;
        }
        //這里硬解出的sw_frame中的圖像格式是23氓辣,對(duì)應(yīng)AV_PIX_FMT_NV12秒裕,所以sw_frame中data[0]存放的是Y數(shù)據(jù),data[1]中存放的是UV交叉數(shù)據(jù)钞啸,和CVPixelBuffer存儲(chǔ)YUV數(shù)據(jù)格式一樣几蜻,可以很方便的轉(zhuǎn)換成CVPixelBuffer
        size = avctx->width * avctx->height;   //這里我遇到一個(gè)小坑癞松,sw_frame中height和視頻的原始高度不符合,導(dǎo)致寫(xiě)入的數(shù)據(jù)不能正常播放入蛆,這里用了解碼器上下文的寬和高
        fwrite(tmp_frame->data[0], 1, size, output_file);    
        fwrite(tmp_frame->data[1], 1, size / 2, output_file);   //直接寫(xiě)入yuv文件中,可以使用ffplay進(jìn)行播放硕勿,ffplay -video_size 1920x1080 -pix_fmt nv12 xxx.yuv
    fail:
        av_frame_free(&frame);
        av_frame_free(&sw_frame);
        if (ret < 0) {
            return ret;
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末哨毁,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子源武,更是在濱河造成了極大的恐慌扼褪,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粱栖,死亡現(xiàn)場(chǎng)離奇詭異话浇,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)闹究,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門幔崖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人渣淤,你說(shuō)我怎么就攤上這事赏寇。” “怎么了价认?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵嗅定,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我用踩,道長(zhǎng)渠退,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任脐彩,我火速辦了婚禮碎乃,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘丁屎。我一直安慰自己荠锭,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布晨川。 她就那樣靜靜地躺著证九,像睡著了一般。 火紅的嫁衣襯著肌膚如雪共虑。 梳的紋絲不亂的頭發(fā)上愧怜,一...
    開(kāi)封第一講書(shū)人閱讀 51,365評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音妈拌,去河邊找鬼拥坛。 笑死蓬蝶,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的猜惋。 我是一名探鬼主播丸氛,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼著摔!你這毒婦竟也來(lái)了缓窜?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤谍咆,失蹤者是張志新(化名)和其女友劉穎禾锤,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體摹察,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡恩掷,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了供嚎。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片黄娘。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖查坪,靈堂內(nèi)的尸體忽然破棺而出寸宏,到底是詐尸還是另有隱情,我是刑警寧澤偿曙,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布氮凝,位于F島的核電站,受9級(jí)特大地震影響望忆,放射性物質(zhì)發(fā)生泄漏罩阵。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一启摄、第九天 我趴在偏房一處隱蔽的房頂上張望稿壁。 院中可真熱鬧,春花似錦歉备、人聲如沸傅是。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)喧笔。三九已至,卻和暖如春龟再,著一層夾襖步出監(jiān)牢的瞬間书闸,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工利凑, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留浆劲,地道東北人嫌术。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像牌借,于是被迫代替她去往敵國(guó)和親度气。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 引言H264編碼使用 VideoToolbox硬編碼錄制H264視頻 從iOS8開(kāi)始膨报,蘋果將VideoToolbo...
    泥孩兒0107閱讀 1,568評(píng)論 0 0
  • 原文地址:http://blog.csdn.net/yipie/article/details/7912291 摘...
    冬的天閱讀 7,179評(píng)論 1 6
  • 前言 系列文章:《iOS視頻開(kāi)發(fā)(一):視頻采集》《iOS視頻開(kāi)發(fā)(二):視頻H264硬編碼》《iOS視頻開(kāi)發(fā)(三...
    GenoChen閱讀 19,106評(píng)論 11 60
  • 游戲是我們現(xiàn)代人生活中的常見(jiàn)之物丙躏,被賦予了交友,競(jìng)技等不同色彩束凑,游戲中有圈子晒旅,新聞,甚至價(jià)值觀與鄙視鏈汪诉。 但是我真...
    MindChen閱讀 418評(píng)論 1 2
  • 起源 也是偶然的機(jī)會(huì)聽(tīng)到O.S.G的發(fā)布會(huì)废恋,于是和幾個(gè)小伙伴一起前去瞅瞅,于此結(jié)緣O.S.G扒寄。后來(lái)O.S.G有了個(gè)...
    inuyashandy閱讀 476評(píng)論 2 5