libavfilter/af_aresample.c
3a9e227f
 /*
  * Copyright (c) 2011 Stefano Sabatini
  * Copyright (c) 2011 Mina Nagy Zaki
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * resampling audio filter
  */
 
e3c6b612
 #include "libavutil/avstring.h"
1acd2f6b
 #include "libavutil/channel_layout.h"
e3c6b612
 #include "libavutil/opt.h"
b13d39bd
 #include "libavutil/samplefmt.h"
 #include "libavutil/avassert.h"
e96be840
 #include "libswresample/swresample.h"
3a9e227f
 #include "avfilter.h"
4522df52
 #include "audio.h"
3a9e227f
 #include "internal.h"
 
ed93ed5e
 typedef struct AResampleContext {
4f43e9b4
     const AVClass *class;
     int sample_rate_arg;
3a9e227f
     double ratio;
e96be840
     struct SwrContext *swr;
847943bc
     int64_t next_pts;
09024fe6
     int more_data;
3a9e227f
 } AResampleContext;
 
4f43e9b4
 static av_cold int init_dict(AVFilterContext *ctx, AVDictionary **opts)
3a9e227f
 {
     AResampleContext *aresample = ctx->priv;
e3c6b612
     int ret = 0;
 
847943bc
     aresample->next_pts = AV_NOPTS_VALUE;
e3c6b612
     aresample->swr = swr_alloc();
9ba2484e
     if (!aresample->swr) {
         ret = AVERROR(ENOMEM);
         goto end;
     }
3a9e227f
 
4f43e9b4
     if (opts) {
         AVDictionaryEntry *e = NULL;
 
         while ((e = av_dict_get(*opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
ec0e0eb4
             if ((ret = av_opt_set(aresample->swr, e->key, e->value, 0)) < 0)
4f43e9b4
                 goto end;
e3c6b612
         }
4f43e9b4
         av_dict_free(opts);
3a9e227f
     }
4f43e9b4
     if (aresample->sample_rate_arg > 0)
         av_opt_set_int(aresample->swr, "osr", aresample->sample_rate_arg, 0);
e3c6b612
 end:
     return ret;
3a9e227f
 }
 
 static av_cold void uninit(AVFilterContext *ctx)
 {
     AResampleContext *aresample = ctx->priv;
e96be840
     swr_free(&aresample->swr);
3a9e227f
 }
 
1cbf7fb4
 static int query_formats(AVFilterContext *ctx)
 {
     AResampleContext *aresample = ctx->priv;
ad45121d
     enum AVSampleFormat out_format;
     int64_t out_rate, out_layout;
1cbf7fb4
 
     AVFilterLink *inlink  = ctx->inputs[0];
     AVFilterLink *outlink = ctx->outputs[0];
 
2ea8a480
     AVFilterFormats        *in_formats, *out_formats;
     AVFilterFormats        *in_samplerates, *out_samplerates;
     AVFilterChannelLayouts *in_layouts, *out_layouts;
6aaac24d
     int ret;
1cbf7fb4
 
ad45121d
     av_opt_get_sample_fmt(aresample->swr, "osf", 0, &out_format);
     av_opt_get_int(aresample->swr, "osr", 0, &out_rate);
     av_opt_get_int(aresample->swr, "ocl", 0, &out_layout);
2ea8a480
 
     in_formats      = ff_all_formats(AVMEDIA_TYPE_AUDIO);
6aaac24d
     if ((ret = ff_formats_ref(in_formats, &inlink->out_formats)) < 0)
         return ret;
2ea8a480
 
     in_samplerates  = ff_all_samplerates();
6aaac24d
     if ((ret = ff_formats_ref(in_samplerates, &inlink->out_samplerates)) < 0)
         return ret;
2ea8a480
 
     in_layouts      = ff_all_channel_counts();
6aaac24d
     if ((ret = ff_channel_layouts_ref(in_layouts, &inlink->out_channel_layouts)) < 0)
         return ret;
1cbf7fb4
 
b13d39bd
     if(out_rate > 0) {
3cc0f335
         int ratelist[] = { out_rate, -1 };
         out_samplerates = ff_make_format_list(ratelist);
1cbf7fb4
     } else {
         out_samplerates = ff_all_samplerates();
     }
1dbc3e8a
 
6aaac24d
     if ((ret = ff_formats_ref(out_samplerates, &outlink->in_samplerates)) < 0)
         return ret;
b13d39bd
 
     if(out_format != AV_SAMPLE_FMT_NONE) {
3cc0f335
         int formatlist[] = { out_format, -1 };
         out_formats = ff_make_format_list(formatlist);
b13d39bd
     } else
1c600888
         out_formats = ff_all_formats(AVMEDIA_TYPE_AUDIO);
6aaac24d
     if ((ret = ff_formats_ref(out_formats, &outlink->in_formats)) < 0)
         return ret;
b13d39bd
 
     if(out_layout) {
3cc0f335
         int64_t layout_list[] = { out_layout, -1 };
         out_layouts = avfilter_make_format64_list(layout_list);
b13d39bd
     } else
b0050245
         out_layouts = ff_all_channel_counts();
1cbf7fb4
 
6aaac24d
     return ff_channel_layouts_ref(out_layouts, &outlink->in_channel_layouts);
1cbf7fb4
 }
 
 
3a9e227f
 static int config_output(AVFilterLink *outlink)
 {
e96be840
     int ret;
3a9e227f
     AVFilterContext *ctx = outlink->src;
     AVFilterLink *inlink = ctx->inputs[0];
     AResampleContext *aresample = ctx->priv;
ad45121d
     int64_t out_rate, out_layout;
b13d39bd
     enum AVSampleFormat out_format;
b0b7a89b
     char inchl_buf[128], outchl_buf[128];
3a9e227f
 
e96be840
     aresample->swr = swr_alloc_set_opts(aresample->swr,
75492cce
                                         outlink->channel_layout, outlink->format, outlink->sample_rate,
e96be840
                                         inlink->channel_layout, inlink->format, inlink->sample_rate,
                                         0, ctx);
     if (!aresample->swr)
         return AVERROR(ENOMEM);
b0050245
     if (!inlink->channel_layout)
         av_opt_set_int(aresample->swr, "ich", inlink->channels, 0);
     if (!outlink->channel_layout)
         av_opt_set_int(aresample->swr, "och", outlink->channels, 0);
b13d39bd
 
e96be840
     ret = swr_init(aresample->swr);
     if (ret < 0)
         return ret;
3a9e227f
 
ad45121d
     av_opt_get_int(aresample->swr, "osr", 0, &out_rate);
     av_opt_get_int(aresample->swr, "ocl", 0, &out_layout);
     av_opt_get_sample_fmt(aresample->swr, "osf", 0, &out_format);
b13d39bd
     outlink->time_base = (AVRational) {1, out_rate};
 
     av_assert0(outlink->sample_rate == out_rate);
2bd104c7
     av_assert0(outlink->channel_layout == out_layout || !outlink->channel_layout);
b13d39bd
     av_assert0(outlink->format == out_format);
 
3a9e227f
     aresample->ratio = (double)outlink->sample_rate / inlink->sample_rate;
 
3d2adeb6
     av_get_channel_layout_string(inchl_buf,  sizeof(inchl_buf),  inlink ->channels, inlink ->channel_layout);
     av_get_channel_layout_string(outchl_buf, sizeof(outchl_buf), outlink->channels, outlink->channel_layout);
62975afa
 
b0050245
     av_log(ctx, AV_LOG_VERBOSE, "ch:%d chl:%s fmt:%s r:%dHz -> ch:%d chl:%s fmt:%s r:%dHz\n",
            inlink ->channels, inchl_buf,  av_get_sample_fmt_name(inlink->format),  inlink->sample_rate,
            outlink->channels, outchl_buf, av_get_sample_fmt_name(outlink->format), outlink->sample_rate);
3a9e227f
     return 0;
 }
 
a05a44e2
 static int filter_frame(AVFilterLink *inlink, AVFrame *insamplesref)
3a9e227f
 {
e96be840
     AResampleContext *aresample = inlink->dst->priv;
a05a44e2
     const int n_in  = insamplesref->nb_samples;
ea6331b2
     int64_t delay;
     int n_out       = n_in * aresample->ratio + 32;
e96be840
     AVFilterLink *const outlink = inlink->dst->outputs[0];
ea6331b2
     AVFrame *outsamplesref;
f8911b98
     int ret;
e96be840
 
ea6331b2
     delay = swr_get_delay(aresample->swr, outlink->sample_rate);
     if (delay > 0)
09024fe6
         n_out += FFMIN(delay, FFMAX(4096, n_out));
ea6331b2
 
     outsamplesref = ff_get_audio_buffer(outlink, n_out);
 
c90b8809
     if(!outsamplesref) {
         av_frame_free(&insamplesref);
014058ab
         return AVERROR(ENOMEM);
c90b8809
     }
014058ab
 
a05a44e2
     av_frame_copy_props(outsamplesref, insamplesref);
b5bea2f9
     outsamplesref->format                = outlink->format;
6af050d7
     outsamplesref->channels              = outlink->channels;
a05a44e2
     outsamplesref->channel_layout        = outlink->channel_layout;
     outsamplesref->sample_rate           = outlink->sample_rate;
847943bc
 
21d8a80e
     if(insamplesref->pts != AV_NOPTS_VALUE) {
         int64_t inpts = av_rescale(insamplesref->pts, inlink->time_base.num * (int64_t)outlink->sample_rate * inlink->sample_rate, inlink->time_base.den);
         int64_t outpts= swr_next_pts(aresample->swr, inpts);
         aresample->next_pts =
4b5a12a2
         outsamplesref->pts  = ROUNDED_DIV(outpts, inlink->sample_rate);
21d8a80e
     } else {
         outsamplesref->pts  = AV_NOPTS_VALUE;
     }
be97675e
     n_out = swr_convert(aresample->swr, outsamplesref->extended_data, n_out,
                                  (void *)insamplesref->extended_data, n_in);
     if (n_out <= 0) {
a05a44e2
         av_frame_free(&outsamplesref);
         av_frame_free(&insamplesref);
f8911b98
         return 0;
be97675e
     }
 
09024fe6
     aresample->more_data = outsamplesref->nb_samples == n_out; // Indicate that there is probably more data in our buffers
 
a05a44e2
     outsamplesref->nb_samples  = n_out;
be97675e
 
cd7febd3
     ret = ff_filter_frame(outlink, outsamplesref);
a05a44e2
     av_frame_free(&insamplesref);
f8911b98
     return ret;
3a9e227f
 }
 
97da6817
 static int flush_frame(AVFilterLink *outlink, int final, AVFrame **outsamplesref_ret)
 {
     AVFilterContext *ctx = outlink->src;
     AResampleContext *aresample = ctx->priv;
     AVFilterLink *const inlink = outlink->src->inputs[0];
     AVFrame *outsamplesref;
     int n_out = 4096;
     int64_t pts;
 
     outsamplesref = ff_get_audio_buffer(outlink, n_out);
     *outsamplesref_ret = outsamplesref;
     if (!outsamplesref)
         return AVERROR(ENOMEM);
 
     pts = swr_next_pts(aresample->swr, INT64_MIN);
     pts = ROUNDED_DIV(pts, inlink->sample_rate);
 
     n_out = swr_convert(aresample->swr, outsamplesref->extended_data, n_out, final ? NULL : (void*)outsamplesref->extended_data, 0);
     if (n_out <= 0) {
         av_frame_free(&outsamplesref);
         return (n_out == 0) ? AVERROR_EOF : n_out;
     }
 
     outsamplesref->sample_rate = outlink->sample_rate;
     outsamplesref->nb_samples  = n_out;
 
     outsamplesref->pts = pts;
 
     return 0;
 }
 
847943bc
 static int request_frame(AVFilterLink *outlink)
 {
     AVFilterContext *ctx = outlink->src;
     AResampleContext *aresample = ctx->priv;
411689b5
     int ret;
 
09024fe6
     // First try to get data from the internal buffers
     if (aresample->more_data) {
         AVFrame *outsamplesref;
 
         if (flush_frame(outlink, 0, &outsamplesref) >= 0) {
             return ff_filter_frame(outlink, outsamplesref);
         }
     }
     aresample->more_data = 0;
 
     // Second request more data from the input
4982130d
     ret = ff_request_frame(ctx->inputs[0]);
847943bc
 
09024fe6
     // Third if we hit the end flush
847943bc
     if (ret == AVERROR_EOF) {
a05a44e2
         AVFrame *outsamplesref;
86b3435f
 
97da6817
         if ((ret = flush_frame(outlink, 1, &outsamplesref)) < 0)
             return ret;
847943bc
 
c82bb281
         return ff_filter_frame(outlink, outsamplesref);
847943bc
     }
     return ret;
 }
 
4f43e9b4
 static const AVClass *resample_child_class_next(const AVClass *prev)
 {
     return prev ? NULL : swr_get_class();
 }
 
 static void *resample_child_next(void *obj, void *prev)
 {
     AResampleContext *s = obj;
     return prev ? NULL : s->swr;
 }
 
 #define OFFSET(x) offsetof(AResampleContext, x)
 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
 
 static const AVOption options[] = {
     {"sample_rate", NULL, OFFSET(sample_rate_arg), AV_OPT_TYPE_INT, {.i64=0},  0,        INT_MAX, FLAGS },
     {NULL}
 };
 
 static const AVClass aresample_class = {
     .class_name       = "aresample",
     .item_name        = av_default_item_name,
     .option           = options,
     .version          = LIBAVUTIL_VERSION_INT,
     .child_class_next = resample_child_class_next,
     .child_next       = resample_child_next,
 };
 
2d9d4440
 static const AVFilterPad aresample_inputs[] = {
     {
         .name         = "default",
         .type         = AVMEDIA_TYPE_AUDIO,
         .filter_frame = filter_frame,
     },
b211607b
     { NULL }
2d9d4440
 };
 
 static const AVFilterPad aresample_outputs[] = {
     {
         .name          = "default",
         .config_props  = config_output,
         .request_frame = request_frame,
         .type          = AVMEDIA_TYPE_AUDIO,
     },
b211607b
     { NULL }
2d9d4440
 };
 
325f6e0a
 AVFilter ff_af_aresample = {
3a9e227f
     .name          = "aresample",
     .description   = NULL_IF_CONFIG_SMALL("Resample audio data."),
4f43e9b4
     .init_dict     = init_dict,
3a9e227f
     .uninit        = uninit,
1cbf7fb4
     .query_formats = query_formats,
3a9e227f
     .priv_size     = sizeof(AResampleContext),
4f43e9b4
     .priv_class    = &aresample_class,
2d9d4440
     .inputs        = aresample_inputs,
     .outputs       = aresample_outputs,
3a9e227f
 };