Featured image of post 【雷霄骅课程笔记】4 FFmpeg + SDL 视频播放器

【雷霄骅课程笔记】4 FFmpeg + SDL 视频播放器

跟着雷神的课程学习写的一些笔记

|
1963 字
|

FFmpeg 和 SDL 整合实现视频播放器

视频链接

整合方式

  • FFmpeg 解码器实现了:视频文件 -> YUV
  • SDL 视频显示实现了:YUV -> 屏幕
  • 整合:FFmpeg + SDL = 视频文件 -> 屏幕

代码运行

代码

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
extern "C"
{
#include <SDL2/SDL.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
}

const int bpp = 12;

int screen_w = 500, screen_h = 500;
const int pixel_w = 320, pixel_h = 180;

unsigned char buffer[pixel_w * pixel_h * bpp / 8];

// SDL_USEREVENT是SDL库中预定义的一个用户事件起始值
// 刷新事件
#define REFRESH_EVENT (SDL_USEREVENT + 1)
// 中断事件
#define BREAK_EVENT (SDL_USEREVENT + 2)

// 线程退出标志
int thread_exit = 0;

int refresh_video(void *opaque)
{
    thread_exit = 0;
    while (!thread_exit)
    {
        SDL_Event event;
        event.type = REFRESH_EVENT;
        SDL_PushEvent(&event);
        SDL_Delay(40);
    }
    thread_exit = 0;
    // 推送一个退出主线程的事件
    SDL_Event event;
    event.type = BREAK_EVENT;
    SDL_PushEvent(&event);

    return 0;
}

int main(int argc, char *argv[])
{
    AVFormatContext *pFormatCtx = NULL;
    int videoindex = -1;
    AVCodecContext *pCodecCtx = NULL;
    const AVCodec *pCodec = NULL;
    AVFrame *pFrame = NULL, *pFrameYUV = NULL;
    unsigned char *out_buffer = NULL;
    AVPacket *packet = NULL;
    int ret = 0;
    struct SwsContext *img_convert_ctx = NULL;

    char filepath[] = "../video/Titanic.ts";

    FILE *fp_yuv = fopen("output.yuv", "wb+");

    // 初始化FFmpeg库
    avformat_network_init();

    // 打开输入文件
    if (avformat_open_input(&pFormatCtx, filepath, NULL, NULL) != 0)
    {
        printf("Couldn't open input stream.\n");
        return -1;
    }

    // 获取流信息
    if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
    {
        printf("Couldn't find stream information.\n");
        return -1;
    }

    printf("时长:%ld\n", pFormatCtx->duration);

    // 查找视频流
    for (int i = 0; i < pFormatCtx->nb_streams; i++)
    {
        if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoindex = i;
            break;
        }
    }

    if (videoindex == -1)
    {
        printf("Didn't find a video stream.\n");
        return -1;
    }

    // 获取解码器
    pCodec = avcodec_find_decoder(pFormatCtx->streams[videoindex]->codecpar->codec_id);
    if (pCodec == NULL)
    {
        printf("Codec not found.\n");
        return -1;
    }

    // 创建解码器上下文
    pCodecCtx = avcodec_alloc_context3(pCodec);
    if (!pCodecCtx)
    {
        printf("Could not allocate video codec context\n");
        return -1;
    }

    // 复制流参数到解码器上下文
    if (avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[videoindex]->codecpar) < 0)
    {
        printf("Could not copy codec parameters to context\n");
        return -1;
    }

    // 打开解码器
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
    {
        printf("Could not open codec.\n");
        return -1;
    }

    pFrame = av_frame_alloc();
    pFrameYUV = av_frame_alloc();
    out_buffer = (unsigned char *)av_malloc(
        av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1));
    av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, out_buffer, AV_PIX_FMT_YUV420P,
                         pCodecCtx->width, pCodecCtx->height, 1);

    packet = av_packet_alloc();

    // 输出文件信息
    printf("--------------- File Information ----------------\n");
    av_dump_format(pFormatCtx, 0, filepath, 0);
    printf("-------------------------------------------------\n");

    img_convert_ctx =
        sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width,
                       pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);

    //==================SDL==================
    // 初始化 SDL 库
    if (SDL_Init(SDL_INIT_VIDEO))
    {
        printf("Could not initialize SDL - %s\n", SDL_GetError());
        return -1;
    }

    // 创建一个窗口
    SDL_Window *screen;
    // SDL 2.0 Support for multiple windows
    screen_w = pCodecCtx->width;
    screen_h = pCodecCtx->height;
    screen =
        SDL_CreateWindow("Simplest Video Play SDL2", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                         screen_w, screen_h, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (!screen)
    {
        printf("SDL: could not create window - exiting:%s\n", SDL_GetError());
        return -1;
    }
    // 创建一个渲染器,将窗口与渲染器关联
    SDL_Renderer *sdlRenderer = SDL_CreateRenderer(screen, -1, 0);

    Uint32 pixformat = 0;

    // IYUV: Y + U + V  (3 planes)
    // YV12: Y + V + U  (3 planes)
    // 设置像素格式
    // SDL_PIXELFORMAT_IYUV 表示使用 YUV420
    pixformat = SDL_PIXELFORMAT_IYUV;

    // 创建纹理,用于存储视频数据
    SDL_Texture *sdlTexture = SDL_CreateTexture(sdlRenderer, pixformat, SDL_TEXTUREACCESS_STREAMING,
                                                pCodecCtx->width, pCodecCtx->height);

    SDL_Rect sdlRect;

    // 创建一个子线程,用于定时触发视频刷新事件
    // 第一个参数是函数指针
    SDL_Thread *refresh_thread = SDL_CreateThread(refresh_video, NULL, NULL);
    SDL_Event event;

    while (1)
    {
        SDL_WaitEvent(&event);
        if (event.type == REFRESH_EVENT)
        {
            while (1)
            {
                if ((av_read_frame(pFormatCtx, packet) < 0))
                    thread_exit = 1;
                if (packet->stream_index == videoindex)
                    break;
            }

            ret = avcodec_send_packet(pCodecCtx, packet);
            if (ret < 0)
            {
                printf("Error sending a packet for decoding\n");
                return -1;
            }

            while (ret >= 0)
            {
                ret = avcodec_receive_frame(pCodecCtx, pFrame);
                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                    break;
                else if (ret < 0)
                {
                    printf("Error during decoding\n");
                    return -1;
                }

                sws_scale(img_convert_ctx, (const unsigned char *const *)pFrame->data,
                          pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data,
                          pFrameYUV->linesize);

                int y_size = pCodecCtx->width * pCodecCtx->height;
                // U V 是分量,宽高各压缩一半,所以大小是 Y 的 1/4

                SDL_UpdateTexture(sdlTexture, NULL, pFrameYUV->data[0], pFrameYUV->linesize[0]);

                // FIX: If window is resize
                sdlRect.x = 0;
                sdlRect.y = 0;
                sdlRect.w = screen_w;
                sdlRect.h = screen_h;

                SDL_RenderClear(sdlRenderer);
                SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, &sdlRect);
                SDL_RenderPresent(sdlRenderer);
                printf("Succeed to decode 1 frame!\n");
            }

            av_packet_unref(packet);
        }
        // SDL_WINDOWEVENT 当窗口大小改变时,更新屏幕宽度和高度
        else if (event.type == SDL_WINDOWEVENT)
        {
            // window
            SDL_GetWindowSize(screen, &screen_w, &screen_h);
        }
        // 当用户关闭窗口时,设置退出标志使子线程退出
        else if (event.type == SDL_QUIT)
        {
            thread_exit = 1;
        }
        // 当接收到退出事件时,退出主循环并释放资源
        // 这个退出事件由子线程提供
        else if (event.type == BREAK_EVENT)
        {
            break;
        }
    }

    // 刷新解码器
    avcodec_send_packet(pCodecCtx, NULL);
    while (ret >= 0)
    {
        ret = avcodec_receive_frame(pCodecCtx, pFrame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            break;
        else if (ret < 0)
        {
            printf("Error during decoding\n");
            return -1;
        }

        sws_scale(img_convert_ctx, (const unsigned char *const *)pFrame->data, pFrame->linesize, 0,
                  pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);

        int y_size = pCodecCtx->width * pCodecCtx->height;
        fwrite(pFrameYUV->data[0], 1, y_size, fp_yuv);     // Y
        fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv); // U
        fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv); // V

        printf("Flush Decoder: Succeed to decode 1 frame!\n");
    }

    sws_freeContext(img_convert_ctx);

    fclose(fp_yuv);

    av_frame_free(&pFrameYUV);
    av_frame_free(&pFrame);
    av_packet_free(&packet);
    avcodec_free_context(&pCodecCtx);
    avformat_close_input(&pFormatCtx);

    return 0;
}

CMakeLists.txt

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
cmake_minimum_required(VERSION 3.10)

project(MyProject VERSION 1.0)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_BUILD_TYPE DEBUG)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# 添加头文件路径
include_directories(${PROJECT_SOURCE_DIR}/include)

# 添加库文件路径
link_directories(${PROJECT_SOURCE_DIR}/lib)

# 添加可执行文件
add_executable(main src/testPlayer.cpp)

# 链接 FFmpeg 库
target_link_libraries(main
    avutil
    avcodec
    avformat
    swscale
)

# 链接 SDL 库
target_link_libraries(main
    SDL2
    SDL2main
)

代码分析

这段代码主要是整合我们前面所写的解码器和 SDL 视频播放器
主要注意下面的几点

1. 纹理数据

在创建纹理和更新纹理时,要给视频的数据,换成前面解码出来的视频数据就行

1
2
3
4
5
6
// 创建纹理,用于存储视频数据
    SDL_Texture *sdlTexture = SDL_CreateTexture(sdlRenderer, pixformat, SDL_TEXTUREACCESS_STREAMING,
                                                pCodecCtx->width, pCodecCtx->height);

// 更新纹理
SDL_UpdateTexture(sdlTexture, NULL, pFrameYUV->data[0], pFrameYUV->linesize[0]);    

2. 循环读取一帧数据

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
while (1)
    {
        SDL_WaitEvent(&event);
        if (event.type == REFRESH_EVENT)
        {
            while (1)
            {
                if ((av_read_frame(pFormatCtx, packet) < 0))
                    thread_exit = 1; 
                if (packet->stream_index == videoindex)
                    break;
            }
        ...
        }
    ...
    }

外层循环如果使用 while(av_read_frame(pFormatCtx, packet) >= 0) 可能导致的问题:

  1. 解码流程混乱:
  • 原代码采用事件驱动模型,由独立线程定时触发刷新事件,保证按正确帧率解码和渲染。

  • 修改后的外层 while (av_read_frame(...)) 循环破坏了原有同步机制,导致:

    • 过快读取 Packet :可能连续发送多个 Packet 到解码器,未等待 SDL 渲染完成
    • 未处理 B 帧依赖:H.264 的 B 帧需要前后参考帧,若解码顺序错误,导致参考帧丢失(reference picture missing)
  1. SDL事件处理冲突:
  • 外层循环强制不断读取 Packet ,可能覆盖正在处理的数据,导致多线程竞争
  • SDL_WaitEvent 在内层阻塞时,外层循环可能持续读取,导致 Packet 堆积或处理顺序错乱

代码也可以改成这样:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
while (1)
    {
        SDL_WaitEvent(&event);
        if (event.type == REFRESH_EVENT)
        {
            while (av_read_frame(pFormatCtx, packet) >= 0)
            {
                if (packet->stream_index == videoindex)
                {
                    ...
                }
                ...
            }
            ...
        }
        ...
    }

可能更清楚一点

使用 Hugo 构建
主题 StackJimmy 设计