[FFmpeg-devel] [PATCH] avcodec/bsf: Avoid allocation for AVBSFInternal

Nicolas George george at nsup.org
Tue Aug 11 01:13:06 EEST 2020


Andreas Rheinhardt (12020-08-10):
> by allocating it together with the AVBSFContext.
> 
> Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt at gmail.com>
> ---
> Similar things can of course be done with other structures. I did only
> this one to see whether everyone is ok with this.

I wholeheartedly approve.


>  libavcodec/bsf.c | 25 +++++++++++++------------
>  1 file changed, 13 insertions(+), 12 deletions(-)
> 
> diff --git a/libavcodec/bsf.c b/libavcodec/bsf.c
> index d71bc32584..9781be78e7 100644
> --- a/libavcodec/bsf.c
> +++ b/libavcodec/bsf.c
> @@ -37,6 +37,11 @@ struct AVBSFInternal {
>      int eof;
>  };
>  
> +typedef struct AVBSFCombined {
> +    AVBSFContext bsf;
> +    AVBSFInternal internal;
> +} AVBSFCombined;
> +
>  void av_bsf_free(AVBSFContext **pctx)
>  {
>      AVBSFContext *ctx;
> @@ -50,9 +55,8 @@ void av_bsf_free(AVBSFContext **pctx)
>      if (ctx->filter->priv_class && ctx->priv_data)
>          av_opt_free(ctx->priv_data);
>  
> -    if (ctx->internal)
> -        av_packet_free(&ctx->internal->buffer_pkt);
> -    av_freep(&ctx->internal);

> +    av_assert2(ctx->internal);

av_assert2(ctx->internal == &((AVBSFCombined *)ctx)->internal);

would be even safer.

> +    av_packet_free(&ctx->internal->buffer_pkt);
>      av_freep(&ctx->priv_data);
>  
>      avcodec_parameters_free(&ctx->par_in);
> @@ -93,14 +97,18 @@ const AVClass *av_bsf_get_class(void)
>  
>  int av_bsf_alloc(const AVBitStreamFilter *filter, AVBSFContext **pctx)
>  {
> +    AVBSFCombined *com;
>      AVBSFContext *ctx;
>      AVBSFInternal *bsfi;
>      int ret;
>  
> -    ctx = av_mallocz(sizeof(*ctx));
> -    if (!ctx)
> +    com = av_mallocz(sizeof(*com));
> +    if (!com)
>          return AVERROR(ENOMEM);
>  
> +    ctx  = &com->bsf;
> +    bsfi = ctx->internal = &com->internal;
> +
>      ctx->av_class = &bsf_class;
>      ctx->filter   = filter;
>  
> @@ -111,13 +119,6 @@ int av_bsf_alloc(const AVBitStreamFilter *filter, AVBSFContext **pctx)
>          goto fail;
>      }
>  
> -    bsfi = av_mallocz(sizeof(*bsfi));
> -    if (!bsfi) {
> -        ret = AVERROR(ENOMEM);
> -        goto fail;
> -    }
> -    ctx->internal = bsfi;
> -
>      bsfi->buffer_pkt = av_packet_alloc();
>      if (!bsfi->buffer_pkt) {
>          ret = AVERROR(ENOMEM);

Regards,

-- 
  Nicolas George
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://ffmpeg.org/pipermail/ffmpeg-devel/attachments/20200811/6299461f/attachment.sig>


More information about the ffmpeg-devel mailing list