FFmpeg+SDL2實現(xiàn)視頻流播放

SDL2文章列表

SDL2入門

SDL2事件處理

SDL2紋理渲染

SDL2音頻播放

本篇博客使用FFmpeg+SDL2完成播放視頻流Demo(僅播放視頻),所有相關(guān)知識在之前的博客中都有提到穴张,稍作整理完成细燎。

流程圖:

FFmpeg解碼視頻流:

SDL2顯示YUV數(shù)據(jù):

源碼

#include <stdio.h>
#include <SDL.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>

int WinMain(int argc, char *argv[]) {
    int ret = -1;
    char *file = "C:\\Users\\lenovo\\Desktop\\fengjing.mp4";
    
    AVFormatContext *pFormatCtx = NULL; 
    int i, videoStream;
    AVCodecParameters *pCodecParameters = NULL; 
    AVCodecContext *pCodecCtx = NULL;
    AVCodec *pCodec = NULL;
    AVFrame *pFrame = NULL;
    AVPacket packet;

    SDL_Rect rect;
    Uint32 pixformat;
    SDL_Window *win = NULL;
    SDL_Renderer *renderer = NULL;
    SDL_Texture *texture = NULL;
    
    //默認窗口大小
    int w_width = 640;
    int w_height = 480;
    
    //SDL初始化
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not initialize SDL - %s\n", SDL_GetError());
        return ret;
    }


    // 打開輸入文件
    if (avformat_open_input(&pFormatCtx, file, NULL, NULL) != 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open  video file!");
        goto __FAIL; 
    }

    //找到視頻流
    videoStream = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    if (videoStream == -1) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Din't find a video stream!");
        goto __FAIL;// Didn't find a video stream
    }

    // 流參數(shù)
    pCodecParameters = pFormatCtx->streams[videoStream]->codecpar;

    //獲取解碼器
    pCodec = avcodec_find_decoder(pCodecParameters->codec_id);
    if (pCodec == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unsupported codec!\n");
        goto __FAIL; // Codec not found
    }

    // 初始化一個編解碼上下文
    pCodecCtx = avcodec_alloc_context3(pCodec);
    if (avcodec_parameters_to_context(pCodecCtx, pCodecParameters) != 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't copy codec context");
        goto __FAIL;// Error copying codec context
    }

    // 打開解碼器
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to open decoder!\n");
        goto __FAIL; // Could not open codec
    }

    // Allocate video frame
    pFrame = av_frame_alloc();

    w_width = pCodecCtx->width;
    w_height = pCodecCtx->height;

    //創(chuàng)建窗口
    win = SDL_CreateWindow("Media Player",
                           SDL_WINDOWPOS_UNDEFINED,
                           SDL_WINDOWPOS_UNDEFINED,
                           w_width, w_height,
                           SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (!win) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to create window by SDL");
        goto __FAIL;
    }

    //創(chuàng)建渲染器
    renderer = SDL_CreateRenderer(win, -1, 0);
    if (!renderer) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to create Renderer by SDL");
        goto __FAIL;
    }

    pixformat = SDL_PIXELFORMAT_IYUV;//YUV格式
    // 創(chuàng)建紋理
    texture = SDL_CreateTexture(renderer,
                                pixformat,
                                SDL_TEXTUREACCESS_STREAMING,
                                w_width,
                                w_height);


    //讀取數(shù)據(jù)
    while (av_read_frame(pFormatCtx, &packet) >= 0) {
        if (packet.stream_index == videoStream) {
            //解碼
            avcodec_send_packet(pCodecCtx, &packet);
            while (avcodec_receive_frame(pCodecCtx, pFrame) == 0) {

                SDL_UpdateYUVTexture(texture, NULL,
                                     pFrame->data[0], pFrame->linesize[0],
                                     pFrame->data[1], pFrame->linesize[1],
                                     pFrame->data[2], pFrame->linesize[2]);

                // Set Size of Window
                rect.x = 0;
                rect.y = 0;
                rect.w = pCodecCtx->width;
                rect.h = pCodecCtx->height;

                //展示
                SDL_RenderClear(renderer);
                SDL_RenderCopy(renderer, texture, NULL, &rect);
                SDL_RenderPresent(renderer);
            }
        }

        av_packet_unref(&packet);

        // 事件處理
        SDL_Event event;
        SDL_PollEvent(&event);
        switch (event.type) {
            case SDL_QUIT:
                goto __QUIT;
            default:
                break;
        }


    }

    __QUIT:
    ret = 0;

    __FAIL:
    // Free the YUV frame
    if (pFrame) {
        av_frame_free(&pFrame);
    }

    // Close the codec
    if (pCodecCtx) {
        avcodec_close(pCodecCtx);
    }

    if (pCodecParameters) {
        avcodec_parameters_free(&pCodecParameters);
    }

    // Close the video file
    if (pFormatCtx) {
        avformat_close_input(&pFormatCtx);
    }

    if (win) {
        SDL_DestroyWindow(win);
    }

    if (renderer) {
        SDL_DestroyRenderer(renderer);
    }

    if (texture) {
        SDL_DestroyTexture(texture);
    }

    SDL_Quit();

    return ret;
}

這個Demo目前只是通過一個while循環(huán)將視頻播放出來,所以可以播放視頻但是速度不正常皂甘,并且沒有聲音玻驻,這些問題會在后面一一解決,最后完成一個簡易的播放器偿枕。

源碼 GitHub-SimplePlayer

====== 更新 2019-04-25璧瞬,線程操作,使畫面顯示40ms一幀=======

# define REFRESH_EVENT  (SDL_USEREVENT + 1) //刷新事件
# define BREAK_EVENT  (SDL_USEREVENT + 2) // 退出事件

int thread_exit = 0;
int thread_pause = 0;

//線程每40ms刷新一次
int video_refresh_thread(void *data) {
    thread_exit = 0;
    thread_pause = 0;

    while (!thread_exit) {
        if (!thread_pause) {
            SDL_Event event;
            event.type = REFRESH_EVENT;
            SDL_PushEvent(&event);// 發(fā)送刷新事件
        }
        SDL_Delay(40);
    }
    thread_exit = 0;
    thread_pause = 0;
    //Break
    SDL_Event event;
    event.type = BREAK_EVENT;
    SDL_PushEvent(&event);

    return 0;
}
//創(chuàng)建線程
SDL_CreateThread(video_refresh_thread, "Video Thread", NULL);

for (;;) {
    SDL_WaitEvent(&event);//使用時間驅(qū)動渐夸,每40ms執(zhí)行一次
    if (event.type == REFRESH_EVENT) {
        while (1) {
            if (av_read_frame(pFormatCtx, &packet) < 0) 
                thread_exit = 1;
           
            if (packet.stream_index == videoStream)
                break;
        }

        if (packet.stream_index == videoStream) {
            avcodec_send_packet(pCodecCtx, &packet);
            while (avcodec_receive_frame(pCodecCtx, pFrame) == 0) {

                SDL_UpdateYUVTexture(texture, NULL,
                                     pFrame->data[0], pFrame->linesize[0],
                                     pFrame->data[1], pFrame->linesize[1],
                                     pFrame->data[2], pFrame->linesize[2]);

                // Set Size of Window
                rect.x = 0;
                rect.y = 0;
                rect.w = pCodecCtx->width;
                rect.h = pCodecCtx->height;

                SDL_RenderClear(renderer);
                SDL_RenderCopy(renderer, texture, NULL, &rect);
                SDL_RenderPresent(renderer);
            }
            av_packet_unref(&packet);
        }
    } else if (event.type == SDL_KEYDOWN) {
        if (event.key.keysym.sym == SDLK_SPACE) { //空格鍵暫停
            thread_pause = !thread_pause;
        }
        if (event.key.keysym.sym== SDLK_ESCAPE){ // ESC鍵退出
            thread_exit = 1;
        }
    } else if (event.type == SDL_QUIT) {
        thread_exit = 1;
    } else if (event.type == BREAK_EVENT) {
        break;
    }
}

通過創(chuàng)建一個線程嗤锉,每隔40ms發(fā)送一次事件,使得視頻播放為40ms一幀墓塌,畫面速度正常瘟忱,播放流暢。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末苫幢,一起剝皮案震驚了整個濱河市访诱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌韩肝,老刑警劉巖触菜,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異伞梯,居然都是意外死亡玫氢,警方通過查閱死者的電腦和手機帚屉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來漾峡,“玉大人攻旦,你說我怎么就攤上這事∩荩” “怎么了牢屋?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長槽袄。 經(jīng)常有香客問我烙无,道長,這世上最難降的妖魔是什么遍尺? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任截酷,我火速辦了婚禮,結(jié)果婚禮上乾戏,老公的妹妹穿的比我還像新娘迂苛。我一直安慰自己,他們只是感情好鼓择,可當(dāng)我...
    茶點故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布三幻。 她就那樣靜靜地躺著,像睡著了一般呐能。 火紅的嫁衣襯著肌膚如雪念搬。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天摆出,我揣著相機與錄音朗徊,去河邊找鬼。 笑死懊蒸,一個胖子當(dāng)著我的面吹牛荣倾,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播骑丸,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼舌仍,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了通危?” 一聲冷哼從身側(cè)響起铸豁,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎菊碟,沒想到半個月后节芥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年头镊,在試婚紗的時候發(fā)現(xiàn)自己被綠了空另。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片孽水。...
    茶點故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡苛秕,死狀恐怖姜凄,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情坛芽,我是刑警寧澤留储,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站咙轩,受9級特大地震影響获讳,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜活喊,卻給世界環(huán)境...
    茶點故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一丐膝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧胧弛,春花似錦尤误、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽软棺。三九已至红竭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間喘落,已是汗流浹背茵宪。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留瘦棋,地道東北人稀火。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像赌朋,于是被迫代替她去往敵國和親凰狞。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,630評論 2 359

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