Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >ffplay源码分析5-图像格式转换

ffplay源码分析5-图像格式转换

作者头像
叶余
发布于 2019-04-02 07:46:09
发布于 2019-04-02 07:46:09
1.2K00
代码可运行
举报
运行总次数:0
代码可运行

5. 图像格式转换

FFmpeg解码得到的视频帧的格式未必能被SDL支持,在这种情况下,需要进行图像格式转换,即将视频帧图像格式转换为SDL支持的图像格式,否则是无法正常显示的。

图像格式转换是在视频播放线程(主线程中)中的upload_texture()函数中实现的。调用链如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
main() -- >
event_loop -->
refresh_loop_wait_event() -->
video_refresh() -->
video_display() -->
video_image_display() -->
upload_texture()

upload_texture()

upload_texture()源码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
static int upload_texture(SDL_Texture **tex, AVFrame *frame, struct SwsContext **img_convert_ctx) {
    int ret = 0;
    Uint32 sdl_pix_fmt;
    SDL_BlendMode sdl_blendmode;
    // 根据frame中的图像格式(FFmpeg像素格式),获取对应的SDL像素格式
    get_sdl_pix_fmt_and_blendmode(frame->format, &sdl_pix_fmt, &sdl_blendmode);
    // 参数tex实际是&is->vid_texture,此处根据得到的SDL像素格式,为&is->vid_texture
    if (realloc_texture(tex, sdl_pix_fmt == SDL_PIXELFORMAT_UNKNOWN ? SDL_PIXELFORMAT_ARGB8888 : sdl_pix_fmt, frame->width, frame->height, sdl_blendmode, 0) < 0)
        return -1;
    switch (sdl_pix_fmt) {
        // frame格式是SDL不支持的格式,则需要进行图像格式转换,转换为目标格式AV_PIX_FMT_BGRA,对应SDL_PIXELFORMAT_BGRA32
        case SDL_PIXELFORMAT_UNKNOWN:
            /* This should only happen if we are not using avfilter... */
            *img_convert_ctx = sws_getCachedContext(*img_convert_ctx,
                frame->width, frame->height, frame->format, frame->width, frame->height,
                AV_PIX_FMT_BGRA, sws_flags, NULL, NULL, NULL);
            if (*img_convert_ctx != NULL) {
                uint8_t *pixels[4];
                int pitch[4];
                if (!SDL_LockTexture(*tex, NULL, (void **)pixels, pitch)) {
                    sws_scale(*img_convert_ctx, (const uint8_t * const *)frame->data, frame->linesize,
                              0, frame->height, pixels, pitch);
                    SDL_UnlockTexture(*tex);
                }
            } else {
                av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");
                ret = -1;
            }
            break;
        // frame格式对应SDL_PIXELFORMAT_IYUV,不用进行图像格式转换,调用SDL_UpdateYUVTexture()更新SDL texture
        case SDL_PIXELFORMAT_IYUV:
            if (frame->linesize[0] > 0 && frame->linesize[1] > 0 && frame->linesize[2] > 0) {
                ret = SDL_UpdateYUVTexture(*tex, NULL, frame->data[0], frame->linesize[0],
                                                       frame->data[1], frame->linesize[1],
                                                       frame->data[2], frame->linesize[2]);
            } else if (frame->linesize[0] < 0 && frame->linesize[1] < 0 && frame->linesize[2] < 0) {
                ret = SDL_UpdateYUVTexture(*tex, NULL, frame->data[0] + frame->linesize[0] * (frame->height                    - 1), -frame->linesize[0],
                                                       frame->data[1] + frame->linesize[1] * (AV_CEIL_RSHIFT(frame->height, 1) - 1), -frame->linesize[1],
                                                       frame->data[2] + frame->linesize[2] * (AV_CEIL_RSHIFT(frame->height, 1) - 1), -frame->linesize[2]);
            } else {
                av_log(NULL, AV_LOG_ERROR, "Mixed negative and positive linesizes are not supported.\n");
                return -1;
            }
            break;
        // frame格式对应其他SDL像素格式,不用进行图像格式转换,调用SDL_UpdateTexture()更新SDL texture
        default:
            if (frame->linesize[0] < 0) {
                ret = SDL_UpdateTexture(*tex, NULL, frame->data[0] + frame->linesize[0] * (frame->height - 1), -frame->linesize[0]);
            } else {
                ret = SDL_UpdateTexture(*tex, NULL, frame->data[0], frame->linesize[0]);
            }
            break;
    }
    return ret;
}

frame中的像素格式是FFmpeg中定义的像素格式,FFmpeg中定义的很多像素格式和SDL中定义的很多像素格式其实是同一种格式,只名称不同而已。

根据frame中的像素格式与SDL支持的像素格式的匹配情况,upload_texture()处理三种类型,对应switch语句的三个分支:

1) 如果frame图像格式对应SDL_PIXELFORMAT_IYUV格式,不进行图像格式转换,使用SDL_UpdateYUVTexture()将图像数据更新到&is->vid_texture

2) 如果frame图像格式对应其他被SDL支持的格式(诸如AV_PIX_FMT_RGB32),也不进行图像格式转换,使用SDL_UpdateTexture()将图像数据更新到&is->vid_texture

3) 如果frame图像格式不被SDL支持(即对应SDL_PIXELFORMAT_UNKNOWN),则需要进行图像格式转换

1) 2)两种类型不进行图像格式转换。我们考虑第3)种情况。

5.1 根据映射表获取frame对应SDL中的像素格式

get_sdl_pix_fmt_and_blendmode()

这个函数的作用,获取输入参数format(FFmpeg像素格式)在SDL中的像素格式,取到的SDL像素格式存在输出参数sdl_pix_fmt

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
static void get_sdl_pix_fmt_and_blendmode(int format, Uint32 *sdl_pix_fmt, SDL_BlendMode *sdl_blendmode)
{
    int i;
    *sdl_blendmode = SDL_BLENDMODE_NONE;
    *sdl_pix_fmt = SDL_PIXELFORMAT_UNKNOWN;
    if (format == AV_PIX_FMT_RGB32   ||
        format == AV_PIX_FMT_RGB32_1 ||
        format == AV_PIX_FMT_BGR32   ||
        format == AV_PIX_FMT_BGR32_1)
        *sdl_blendmode = SDL_BLENDMODE_BLEND;
    for (i = 0; i < FF_ARRAY_ELEMS(sdl_texture_format_map) - 1; i++) {
        if (format == sdl_texture_format_map[i].format) {
            *sdl_pix_fmt = sdl_texture_format_map[i].texture_fmt;
            return;
        }
    }
}

在ffplay.c中定义了一个表sdl_texture_format_map[],其中定义了FFmpeg中一些像素格式与SDL像素格式的映射关系,如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
static const struct TextureFormatEntry {
    enum AVPixelFormat format;
    int texture_fmt;
} sdl_texture_format_map[] = {
    { AV_PIX_FMT_RGB8,           SDL_PIXELFORMAT_RGB332 },
    { AV_PIX_FMT_RGB444,         SDL_PIXELFORMAT_RGB444 },
    { AV_PIX_FMT_RGB555,         SDL_PIXELFORMAT_RGB555 },
    { AV_PIX_FMT_BGR555,         SDL_PIXELFORMAT_BGR555 },
    { AV_PIX_FMT_RGB565,         SDL_PIXELFORMAT_RGB565 },
    { AV_PIX_FMT_BGR565,         SDL_PIXELFORMAT_BGR565 },
    { AV_PIX_FMT_RGB24,          SDL_PIXELFORMAT_RGB24 },
    { AV_PIX_FMT_BGR24,          SDL_PIXELFORMAT_BGR24 },
    { AV_PIX_FMT_0RGB32,         SDL_PIXELFORMAT_RGB888 },
    { AV_PIX_FMT_0BGR32,         SDL_PIXELFORMAT_BGR888 },
    { AV_PIX_FMT_NE(RGB0, 0BGR), SDL_PIXELFORMAT_RGBX8888 },
    { AV_PIX_FMT_NE(BGR0, 0RGB), SDL_PIXELFORMAT_BGRX8888 },
    { AV_PIX_FMT_RGB32,          SDL_PIXELFORMAT_ARGB8888 },
    { AV_PIX_FMT_RGB32_1,        SDL_PIXELFORMAT_RGBA8888 },
    { AV_PIX_FMT_BGR32,          SDL_PIXELFORMAT_ABGR8888 },
    { AV_PIX_FMT_BGR32_1,        SDL_PIXELFORMAT_BGRA8888 },
    { AV_PIX_FMT_YUV420P,        SDL_PIXELFORMAT_IYUV },
    { AV_PIX_FMT_YUYV422,        SDL_PIXELFORMAT_YUY2 },
    { AV_PIX_FMT_UYVY422,        SDL_PIXELFORMAT_UYVY },
    { AV_PIX_FMT_NONE,           SDL_PIXELFORMAT_UNKNOWN },
};

可以看到,除了最后一项,其他格式的图像送给SDL是可以直接显示的,不必进行图像转换。

关于这些像素格式的含义,可参考“色彩空间与像素格式

5.2 重新分配vid_texture

realloc_texture()

根据新得到的SDL像素格式,为&is->vid_texture重新分配空间,如下所示,先SDL_DestroyTexture()销毁,再SDL_CreateTexture()创建

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
static int realloc_texture(SDL_Texture **texture, Uint32 new_format, int new_width, int new_height, SDL_BlendMode blendmode, int init_texture)
{
    Uint32 format;
    int access, w, h;
    if (!*texture || SDL_QueryTexture(*texture, &format, &access, &w, &h) < 0 || new_width != w || new_height != h || new_format != format) {
        void *pixels;
        int pitch;
        if (*texture)
            SDL_DestroyTexture(*texture);
        if (!(*texture = SDL_CreateTexture(renderer, new_format, SDL_TEXTUREACCESS_STREAMING, new_width, new_height)))
            return -1;
        if (SDL_SetTextureBlendMode(*texture, blendmode) < 0)
            return -1;
        if (init_texture) {
            if (SDL_LockTexture(*texture, NULL, &pixels, &pitch) < 0)
                return -1;
            memset(pixels, 0, pitch * new_height);
            SDL_UnlockTexture(*texture);
        }
        av_log(NULL, AV_LOG_VERBOSE, "Created %dx%d texture with %s.\n", new_width, new_height, SDL_GetPixelFormatName(new_format));
    }
    return 0;
}

5.3 复用或新分配一个SwsContext

sws_getCachedContext()

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
*img_convert_ctx = sws_getCachedContext(*img_convert_ctx,
    frame->width, frame->height, frame->format, frame->width, frame->height,
    AV_PIX_FMT_BGRA, sws_flags, NULL, NULL, NULL);

检查输入参数,第一个输入参数*img_convert_ctx对应形参struct SwsContext *context

如果context是NULL,调用sws_getContext()重新获取一个context。

如果context不是NULL,检查其他项输入参数是否和context中存储的各参数一样,若不一样,则先释放context再按照新的输入参数重新分配一个context。若一样,直接使用现有的context。

5.4 图像格式转换

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
if (*img_convert_ctx != NULL) {
    uint8_t *pixels[4];
    int pitch[4];
    if (!SDL_LockTexture(*tex, NULL, (void **)pixels, pitch)) {
        sws_scale(*img_convert_ctx, (const uint8_t * const *)frame->data, frame->linesize,
                  0, frame->height, pixels, pitch);
        SDL_UnlockTexture(*tex);
    }
}

上述代码有三个步骤:

1) SDL_LockTexture()锁定texture中的一个rect(此处是锁定整个texture),锁定区具有只写属性,用于更新图像数据。pixels指向锁定区。

2) sws_scale()进行图像格式转换,转换后的数据写入pixels指定的区域。pixels包含4个指针,指向一组图像plane。

3) SDL_UnlockTexture()将锁定的区域解锁,将改变的数据更新到视频缓冲区中。

上述三步完成后,texture中已包含经过格式转换后新的图像数据。

补充一下细节,sws_scale()函数原型如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * Scale the image slice in srcSlice and put the resulting scaled
 * slice in the image in dst. A slice is a sequence of consecutive
 * rows in an image.
 *
 * Slices have to be provided in sequential order, either in
 * top-bottom or bottom-top order. If slices are provided in
 * non-sequential order the behavior of the function is undefined.
 *
 * @param c         the scaling context previously created with
 *                  sws_getContext()
 * @param srcSlice  the array containing the pointers to the planes of
 *                  the source slice
 * @param srcStride the array containing the strides for each plane of
 *                  the source image
 * @param srcSliceY the position in the source image of the slice to
 *                  process, that is the number (counted starting from
 *                  zero) in the image of the first row of the slice
 * @param srcSliceH the height of the source slice, that is the number
 *                  of rows in the slice
 * @param dst       the array containing the pointers to the planes of
 *                  the destination image
 * @param dstStride the array containing the strides for each plane of
 *                  the destination image
 * @return          the height of the output slice
 */
int sws_scale(struct SwsContext *c, const uint8_t *const srcSlice[],
              const int srcStride[], int srcSliceY, int srcSliceH,
              uint8_t *const dst[], const int dstStride[]);

5.5 图像显示

texture对应一帧待显示的图像数据,得到texture后,执行如下步骤即可显示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
SDL_RenderClear();                  // 使用特定颜色清空当前渲染目标
SDL_RenderCopy();                   // 使用部分图像数据(texture)更新当前渲染目标
SDL_RenderPresent(sdl_renderer);    // 执行渲染,更新屏幕显示

图像显示的流程细节可参考如下文章:

FFmpeg简易播放器的实现-视频播放

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-01-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
vue2升级vue3:Vue Demij打通vue2与vue3壁垒,构建通用组件
如果你的vue2代码之前是使用vue-class-component 类组件模式写的。选择可以使用 https://github.com/facing-dev/vue-facing-decorator 来进行低成本的升级,但是升级难度还是蛮大的。
周陆军博客
2022/07/25
1.6K0
vue2升级vue3:vue3真的需要vuex或者Pinia吗?hooks全有了
在写 《vue2升级vue3:TypeScript下vuex-module-decorators/vuex-class to vuex4.x》,建议新项目使用 Pinia,但是我的项目部分组件希望直接打包出去给地方使用。这个时候还是会遇到vue2 是否打包出vuex的 问题。所以,干脆舍弃 vuex/Pinia,直接使用 vue3 原生搞定——hook出现之后,状态管理的问题已经从根本上被消解了!
周陆军博客
2023/01/25
1.1K0
vue2升级vue3:class component的遗憾
但是到vue3,这个class 提案被废止了——GitHub上也停留在rc1版本了,已经2年左右没有提交代码了!
周陆军博客
2022/06/25
1.4K0
vue2升级vue3: TSX Vue 3 Composition API Refs
虽然不推荐这么做,但是确实非常好用。但是vue2快速迁移到vue3,之前的这个写法因为干进度,不想重构,直接搬迁,发现不行?
周陆军博客
2022/07/30
7860
vue2升级vue3:单文件组件概述 及 defineExpos/expose
像我这种react门徒被迫迁移到vue的,用管了TSX,地vue 单文件组件也不太感冒,但是vue3 单文件组件,造了蛮多api ,还不得去了解下
周陆军博客
2022/07/25
2.4K0
vue2升级vue3:组合式 API之Setup(props,context)—Vue2.x到Vue3注意
vue3出来已经很长一段时间,项目已经用起来了。本篇是使用过程的中的一些零零散散的笔记的。
周陆军博客
2022/06/24
1.7K0
vue2升级vue3: Event Bus 替代方案
在看 https://v3-migration.vuejs.org/breaking-changes/events-api.html
周陆军博客
2022/06/25
1.7K0
vue2升级vue3:provide与inject 使用注意事项
provide / inject 类似于消息的订阅和发布。provide 提供或发送数据, inject 接收数据。
周陆军博客
2022/07/25
1.5K0
vue2升级vue3:composition api中监听路由参数改变
《watch性能优化:vue watch对象键值说明-immediate属性详解》
周陆军博客
2022/07/25
1.5K0
vue2升级vue3:vue3创建全局属性和方法
vue2.x挂载全局是使用Vue.prototype.$xxxx=xxx的形式来挂载,然后通过this.$xxx来获取挂载到全局的变量或者方法
周陆军博客
2022/07/25
1.2K0
vue2升级vue3:this.$createElement is not a function—动态组件升级
更多推荐阅读:vue.$createElement的使用实例 https://juejin.cn/post/6969505687114088484
周陆军博客
2022/06/25
2.7K0
vue2升级vue3: 全局变量挂载与类型声明
使用 ts 的情况下,挂载完全局变量后,在 vue 文件中,通过 this 对象 . 出来不来提示的。
周陆军博客
2022/06/25
4960
vue2升级vue3:Vue Router报错,directly inside <transition> or <keep-a
vue-router.mjs:35 [Vue Router warn]: <router-view> can no longer be used directly inside <transition> or <keep-alive>.
周陆军博客
2022/07/25
2.4K0
vue2升级vue3:TypeScript下vuex-module-decorators/vuex-class to vuex4.x
因为vue2 下  vue-property-decorator + vue-tsx-support +vuex-module-decorators/vuex-class ,class components 用的爽的也是不要不要的
周陆军博客
2022/06/25
8420
vue2升级vue3:vue2 vue-i18n 升级到vue3搭配VueI18n v9
项目从vue2 升级vue3,VueI18n需要做适当的调整。主要是Vue I18n v8.x 到Vue I18n v9 or later 的变化,其中初始化:
周陆军博客
2022/06/24
7910
vue2升级vue3:Vue2/3插槽——vue3的jsx组件插槽slot怎么处理
vue 在 2.6 版本中,对插槽使用 v-slot 新语法,取代了旧语法的 slot 和 slot-scope,并且之后的 Vue 3.0 也会使用新语法,这并不是仅写法的不同,还包括了性能的提升
周陆军博客
2022/06/24
2.5K0
vue2升级vue3:Vue3时jsx组件绑定自定义的事件、v-model、sync修
踩坑笔记:组合式 API之Setup(props,context)—Vue2.x到Vue3注意
周陆军博客
2022/06/24
2.7K0
vue2升级vue3: h、createVNode、render、createApp使用
h 函数本质就是 createElement() 的简写,作用是根据配置创建对应的虚拟节点,在vue 中占有极其重要的地位!
周陆军博客
2022/07/25
4.5K0
vue2升级vue3:vue-i18n国际化异步按需加载
vue2异步加载之前说过,vue3还是之前的方法,只是把 i18n.setLocaleMessage改为i18n.global.setLocaleMessage
周陆军博客
2023/03/18
2K0
来自 Vue 官方团队的 57 个技术分享
最近在看 Vue 团队成员的技术演讲,从中能了解到他们的设计思考以及最佳实践,看完一场收获颇多。
Leecason
2022/07/13
1.6K0
来自 Vue 官方团队的 57 个技术分享
推荐阅读
相关推荐
vue2升级vue3:Vue Demij打通vue2与vue3壁垒,构建通用组件
更多 >
交个朋友
加入腾讯云官网粉丝站
蹲全网底价单品 享第一手活动信息
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验