FFMpeg分析:第一个函数avformat_open_input

2023-11-23 04:58

本文主要是介绍FFMpeg分析:第一个函数avformat_open_input,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在上篇文章中的demo中,main函数的流程里调用的第一个函数就是avformat_open_input()。直观看来,其最明显的功能就是制定了要播放的文件名了。但是除了问价名之外还有几个结构体作为了函数的参数。那么这个函数的功能是什么?又是怎么完成的?一起慢慢研究。

先贴代码:

int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
{AVFormatContext *s = *ps;int ret = 0;AVDictionary *tmp = NULL;ID3v2ExtraMeta *id3v2_extra_meta = NULL;if (!s && !(s = avformat_alloc_context()))return AVERROR(ENOMEM);if (!s->av_class){av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");return AVERROR(EINVAL);}if (fmt)s->iformat = fmt;if (options)av_dict_copy(&tmp, *options, 0);if ((ret = av_opt_set_dict(s, &tmp)) < 0)goto fail;if ((ret = init_input(s, filename, &tmp)) < 0)goto fail;s->probe_score = ret;avio_skip(s->pb, s->skip_initial_bytes);/* check filename in case an image number is expected */if (s->iformat->flags & AVFMT_NEEDNUMBER) {if (!av_filename_number_test(filename)) {ret = AVERROR(EINVAL);goto fail;}}s->duration = s->start_time = AV_NOPTS_VALUE;av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));/* allocate private data */if (s->iformat->priv_data_size > 0) {if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))){ret = AVERROR(ENOMEM);goto fail;}if (s->iformat->priv_class) {*(const AVClass**)s->priv_data = s->iformat->priv_class;av_opt_set_defaults(s->priv_data);if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)goto fail;}}/* e.g. AVFMT_NOFILE formats will not have a AVIOContext */if (s->pb)ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)if ((ret = s->iformat->read_header(s)) < 0)goto fail;if (id3v2_extra_meta){if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||!strcmp(s->iformat->name, "tta")) {if((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)goto fail;} elseav_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");}ff_id3v2_free_extra_meta(&id3v2_extra_meta);if ((ret = avformat_queue_attached_pictures(s)) < 0)goto fail;if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)s->data_offset = avio_tell(s->pb);s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;if (options) {av_dict_free(options);*options = tmp;}*ps = s;return 0;fail:ff_id3v2_free_extra_meta(&id3v2_extra_meta);av_dict_free(&tmp);if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))avio_close(s->pb);avformat_free_context(s);*ps = NULL;return ret;
}
函数的各个参数:

1、AVFormatContext **ps:指向用户提供的结构体,一般可以将这个参数定义指向空然后传递到函数中,这样avformat_open_input函数将会分配这个结构体的内存空间并初始化。

2、const char *filename:打开视频文件的文件名。

3、AVInputFormat *fmt:如果这个参数不为空,则指定固定的输入格式,否则自动检测输入格式;一般设为空即可。

4、AVDictionary **options:由AVFormatContext和demuxer-private options组成的字典结构,可设为空。

该函数中调用了init_input()函数实现打开目标文件和检测文件格式等操作,代码如下:

static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
{int ret;AVProbeData pd = {filename, NULL, 0};int score = AVPROBE_SCORE_RETRY;if (s->pb) {s->flags |= AVFMT_FLAG_CUSTOM_IO;if (!s->iformat)return av_probe_input_buffer2(s->pb, &s->iformat, filename, s, 0, s->probesize);else if (s->iformat->flags & AVFMT_NOFILE)av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and ""will be ignored with AVFMT_NOFILE format.\n");return 0;}if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||(!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))return score;if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,&s->interrupt_callback, options)) < 0)return ret;if (s->iformat)return 0;return av_probe_input_buffer2(s->pb, &s->iformat, filename, s, 0, s->probesize);
}
根据条件的不同,该函数内部调用了av_probe_input_buffer2()或avio_open2()两个函数。av_probe_input_buffer2()函数通过分析bitstream来确定输入的格式,代码如下:

int av_probe_input_buffer2(AVIOContext *pb, AVInputFormat **fmt, const char *filename, void *logctx, unsigned int offset, unsigned int max_probe_size)
{AVProbeData pd = { filename ? filename : "", NULL, -offset };unsigned char *buf = NULL;uint8_t *mime_type;int ret = 0, probe_size, buf_offset = 0;int score = 0;if (!max_probe_size) {max_probe_size = PROBE_BUF_MAX;} else if (max_probe_size > PROBE_BUF_MAX) {max_probe_size = PROBE_BUF_MAX;} else if (max_probe_size < PROBE_BUF_MIN) {av_log(logctx, AV_LOG_ERROR,"Specified probe size value %u cannot be < %u\n", max_probe_size, PROBE_BUF_MIN);return AVERROR(EINVAL);}if (offset >= max_probe_size) {return AVERROR(EINVAL);}if (!*fmt && pb->av_class && av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type) >= 0 && mime_type) {if (!av_strcasecmp(mime_type, "audio/aacp")) {*fmt = av_find_input_format("aac");}av_freep(&mime_type);}for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {if (probe_size < offset) {continue;}score = probe_size < max_probe_size ? AVPROBE_SCORE_RETRY : 0;/* read probe data */if ((ret = av_reallocp(&buf, probe_size + AVPROBE_PADDING_SIZE)) < 0)return ret;if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {/* fail if error was not end of file, otherwise, lower score */if (ret != AVERROR_EOF) {av_free(buf);return ret;}score = 0;ret = 0;            /* error was end of file, nothing read */}pd.buf_size = buf_offset += ret;pd.buf = &buf[offset];memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);/* guess file format */*fmt = av_probe_input_format2(&pd, 1, &score);if(*fmt){if(score <= AVPROBE_SCORE_RETRY){ //this can only be true in the last iterationav_log(logctx, AV_LOG_WARNING, "Format %s detected only with low score of %d, misdetection possible!\n", (*fmt)->name, score);}elseav_log(logctx, AV_LOG_DEBUG, "Format %s probed with size=%d and score=%d\n", (*fmt)->name, probe_size, score);}}if (!*fmt) {av_free(buf);return AVERROR_INVALIDDATA;}/* rewind. reuse probe buffer to avoid seeking */ret = ffio_rewind_with_probe_data(pb, &buf, pd.buf_size);return ret < 0 ? ret : score;
}
其中调用了av_probe_input_format2()函数确定输入格式,其具体实现在函数av_probe_input_format3()中。

avio_open2()的代码如下:

int avio_open2(AVIOContext **s, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
{URLContext *h;int err;err = ffurl_open(&h, filename, flags, int_cb, options);if (err < 0)return err;err = ffio_fdopen(s, h);if (err < 0) {ffurl_close(h);return err;}return 0;
}
该函数用于建立和初始化一个AVIOContext结构体,用于打开指定的url指向的资源。各个参数的含义:

1、AVIOContext **s:用于指向返回的AVIOContext结构体的指针,调用时应设为NULL;

2、const char *url:指定资源的地址;考虑本地播放时,就是文件名的字符串的地址;

3、int flags:标志位,控制文件打开的方式;

4、const AVIOInterruptCB *int_cb:在协议层使用的中断回调指针;

5、AVDictionary **options:protocol-private options组成的字典元素,设为空即可。

avio_open2()调用了ffurl_open()函数,创建一个URLContext结构体用于获取并打开url指向的资源(分别调用ffurl_alloc()和ffurl_connect()创建和链接URLContext结构体);调用ffio_fdopen()函数创建AVIOContext()结构体并获取URLContext结构体引用的资源(调用avio_alloc_context()实现);

整个函数的大致框图如下:


在实际运行的过程中,url_read、url_write等函数都由一个URLProtocal实现,代码如下:

typedef struct URLProtocol 
{const char *name;int     (*url_open)( URLContext *h, const char *url, int flags);/*** This callback is to be used by protocols which open further nested* protocols. options are then to be passed to ffurl_open()/ffurl_connect()* for those nested protocols.*/int     (*url_open2)(URLContext *h, const char *url, int flags, AVDictionary **options);/*** Read data from the protocol.* If data is immediately available (even less than size), EOF is* reached or an error occurs (including EINTR), return immediately.* Otherwise:* In non-blocking mode, return AVERROR(EAGAIN) immediately.* In blocking mode, wait for data/EOF/error with a short timeout (0.1s),* and return AVERROR(EAGAIN) on timeout.* Checking interrupt_callback, looping on EINTR and EAGAIN and until* enough data has been read is left to the calling function; see* retry_transfer_wrapper in avio.c.*/int     (*url_read)( URLContext *h, unsigned char *buf, int size);int     (*url_write)(URLContext *h, const unsigned char *buf, int size);int64_t (*url_seek)( URLContext *h, int64_t pos, int whence);int     (*url_close)(URLContext *h);struct URLProtocol *next;int (*url_read_pause)(URLContext *h, int pause);int64_t (*url_read_seek)(URLContext *h, int stream_index,int64_t timestamp, int flags);int (*url_get_file_handle)(URLContext *h);int (*url_get_multi_file_handle)(URLContext *h, int **handles,int *numhandles);int (*url_shutdown)(URLContext *h, int flags);int priv_data_size;const AVClass *priv_data_class;int flags;int (*url_check)(URLContext *h, int mask);
} URLProtocol;
针对不同的协议,分别定义了不同的URLPrococol对象来进行具体的操作,如:

文件协议:

URLProtocol ff_pipe_protocol = {.name                = "pipe",.url_open            = pipe_open,.url_read            = file_read,.url_write           = file_write,.url_get_file_handle = file_get_handle,.url_check           = file_check,.priv_data_size      = sizeof(FileContext),.priv_data_class     = &pipe_class,
};
ftp协议:

URLProtocol ff_ftp_protocol = {.name                = "ftp",.url_open            = ftp_open,.url_read            = ftp_read,.url_write           = ftp_write,.url_seek            = ftp_seek,.url_close           = ftp_close,.url_get_file_handle = ftp_get_file_handle,.url_shutdown        = ftp_shutdown,.priv_data_size      = sizeof(FTPContext),.priv_data_class     = &ftp_context_class,.flags               = URL_PROTOCOL_FLAG_NETWORK,
};
http协议:

URLProtocol ff_http_protocol = {.name                = "http",.url_open2           = http_open,.url_read            = http_read,.url_write           = http_write,.url_seek            = http_seek,.url_close           = http_close,.url_get_file_handle = http_get_file_handle,.url_shutdown        = http_shutdown,.priv_data_size      = sizeof(HTTPContext),.priv_data_class     = &http_context_class,.flags               = URL_PROTOCOL_FLAG_NETWORK,
};
rtmp协议:

URLProtocol ff_librtmp_protocol ={.name                = "rtmp",.url_open            = rtmp_open,.url_read            = rtmp_read,.url_write           = rtmp_write,.url_close           = rtmp_close,.url_read_pause      = rtmp_read_pause,.url_read_seek       = rtmp_read_seek,.url_get_file_handle = rtmp_get_file_handle,.priv_data_size      = sizeof(LibRTMPContext),.priv_data_class     = &librtmp_class,.flags               = URL_PROTOCOL_FLAG_NETWORK,
};


这篇关于FFMpeg分析:第一个函数avformat_open_input的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/415495

相关文章

基于Go语言实现Base62编码的三种方式以及对比分析

《基于Go语言实现Base62编码的三种方式以及对比分析》Base62编码是一种在字符编码中使用62个字符的编码方式,在计算机科学中,,Go语言是一种静态类型、编译型语言,它由Google开发并开源,... 目录一、标准库现状与解决方案1. 标准库对比表2. 解决方案完整实现代码(含边界处理)二、关键实现细

PostgreSQL 序列(Sequence) 与 Oracle 序列对比差异分析

《PostgreSQL序列(Sequence)与Oracle序列对比差异分析》PostgreSQL和Oracle都提供了序列(Sequence)功能,但在实现细节和使用方式上存在一些重要差异,... 目录PostgreSQL 序列(Sequence) 与 oracle 序列对比一 基本语法对比1.1 创建序

Android NDK版本迭代与FFmpeg交叉编译完全指南

《AndroidNDK版本迭代与FFmpeg交叉编译完全指南》在Android开发中,使用NDK进行原生代码开发是一项常见需求,特别是当我们需要集成FFmpeg这样的多媒体处理库时,本文将深入分析A... 目录一、android NDK版本迭代分界线二、FFmpeg交叉编译关键注意事项三、完整编译脚本示例四

Kotlin运算符重载函数及作用场景

《Kotlin运算符重载函数及作用场景》在Kotlin里,运算符重载函数允许为自定义类型重新定义现有的运算符(如+-…)行为,从而让自定义类型能像内置类型那样使用运算符,本文给大家介绍Kotlin运算... 目录基本语法作用场景类对象数据类型接口注意事项在 Kotlin 里,运算符重载函数允许为自定义类型重

慢sql提前分析预警和动态sql替换-Mybatis-SQL

《慢sql提前分析预警和动态sql替换-Mybatis-SQL》为防止慢SQL问题而开发的MyBatis组件,该组件能够在开发、测试阶段自动分析SQL语句,并在出现慢SQL问题时通过Ducc配置实现动... 目录背景解决思路开源方案调研设计方案详细设计使用方法1、引入依赖jar包2、配置组件XML3、核心配

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中