From 5ef0d52dbf2fa16ce3630f320c06eb72d83b6c2c Mon Sep 17 00:00:00 2001
From: Atana <atana@openmailbox.org>
Date: Wed, 2 Nov 2016 04:49:15 +0530
Subject: [PATCH] avfilter: added peakpoints filter

---
 libavfilter/af_peakpoints.c | 300 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 300 insertions(+)
 create mode 100644 libavfilter/af_peakpoints.c

diff --git a/libavfilter/af_peakpoints.c b/libavfilter/af_peakpoints.c
new file mode 100644
index 0000000..e5c4494
--- /dev/null
+++ b/libavfilter/af_peakpoints.c
@@ -0,0 +1,300 @@
+/*
+ * Copyright (c) 2016 Atana
+ *
+ * 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
+ */
+
+#include "libavcodec/avcodec.h"
+#include "libavcodec/avfft.h"
+#include "libavformat/avformat.h"
+#include "libswscale/swscale.h"
+#include "avfilter.h"
+#include "libavutil/opt.h"
+
+
+/* Structure to contain peak points context */
+typedef struct {
+    const AVClass *class;
+    double *data;
+    int nsamples;
+    double *peaks;
+    int size; // number of peaks
+    int windowSize;
+    char *inputFile;
+} PeakPointsContext;
+
+/* returns maximum value from an array conditioned on start and end index */
+static double getMax(double *res_arr, int startIndex, int endIndex) {
+    int i;
+    double max = res_arr[startIndex];
+    for (i = startIndex; i <= endIndex; i++) {
+	    if (res_arr[i] > max) {
+	        max = res_arr[i];
+	    }
+    }
+    return max;
+}
+
+/* Stores peak frequency for each window(of chunkSize) in peaks array */
+static void getPeakPointInChunk(int chunkSize, double *res_arr, int size, double *peaks) {
+    int endIndex, i = 0, peakIndex = 0;
+    int startIndex = 0;
+    double max;
+    // get a chunk and find max value in it
+    while (i < size) {
+	    if (i % chunkSize-1 == 0) {
+            max = getMax(res_arr, startIndex, i);
+	        peaks[peakIndex++] = max;
+	        startIndex = startIndex + chunkSize;
+	    }
+        i += 1;
+    }
+}
+
+/* read audio stream from input file */
+static void readAudio (int *sampleRate, PeakPointsContext *ppc) {
+    // Initialize FFmpeg
+    av_register_all ();
+
+    AVFormatContext *formatContext = NULL;
+    AVCodecContext *codecContext = NULL;
+    AVCodec *codec = NULL;
+    AVPacket packet;
+    AVFrame *frame = av_frame_alloc();
+    void *avc;
+    ssize_t nSamples = 0;
+
+    // open the file and autodetect the format
+    if (avformat_open_input (&formatContext, ppc->inputFile, NULL, NULL) < 0)
+        av_log(avc, AV_LOG_ERROR, "Can not open input file %s", ppc->inputFile);
+
+    if (avformat_find_stream_info (formatContext, NULL) < 0)
+        av_log(avc, AV_LOG_ERROR, "Can not find stream information");
+        // find audio stream (between video/audio/subtitles/.. streams)
+        int audioStreamId = av_find_best_stream (formatContext, AVMEDIA_TYPE_AUDIO,
+                                            -1, -1, &codec, 0);
+    if (audioStreamId < 0)
+        av_log(avc, AV_LOG_ERROR, "Can not find audio stream in the input file");
+
+    codecContext = formatContext->streams[audioStreamId]->codec;
+
+    // init the audio decoder
+    if (avcodec_open2 (codecContext, codec, NULL) < 0)
+        av_log(avc, AV_LOG_ERROR, "Can not open audio decoder");
+
+    // read all packets
+    int i = 0;
+    av_init_packet(&packet);
+    packet.data = NULL;
+    packet.size = 0;
+    while (av_read_frame (formatContext, &packet) == 0)  {
+        if (packet.stream_index == audioStreamId)  {
+            //avcodec_get_frame_defaults (&frame);
+            //av_frame_unref(frame);
+            int gotFrame = 0;
+            if (avcodec_decode_audio4 (codecContext, frame, &gotFrame, &packet) < 0){
+                av_log(avc, AV_LOG_ERROR, "Error decoding audio");
+            }
+
+            if (gotFrame)  {
+                // audio frame has been decoded
+                int size = av_samples_get_buffer_size (NULL,
+                                                   codecContext->channels,
+                                                   frame->nb_samples,
+                                                   codecContext->sample_fmt,
+                                                   1);
+                if (size < 0)  {
+                    av_log(avc, AV_LOG_ERROR, "av_samples_get_buffer_size invalid value");
+                }
+
+                ppc->data[i] = (double)*frame->data[0];
+                i += 1;
+                nSamples += frame->nb_samples;
+            }
+        }
+        av_free_packet (&packet);
+    }
+    ppc->nsamples = i;
+
+    if (nSamples < 1)
+        av_log(avc, AV_LOG_WARNING, "Decoded audio data is empty");
+
+    int sampleSize = av_get_bytes_per_sample (codecContext->sample_fmt);
+    if (sampleSize < 1)
+        av_log(avc, AV_LOG_WARNING, "Invalid sample format");
+
+    // optional, return value with sample rate
+    if (sampleRate) *sampleRate = codecContext->sample_rate;
+
+    if (codecContext) avcodec_close (codecContext);
+
+    if (frame) {
+        av_free(frame);
+        frame = NULL;
+    }
+    avformat_close_input (&formatContext);
+}
+
+/* Get peaks points from windowed frequency domain data*/
+static int getPeakPoints(PeakPointsContext *ppc) {
+    int i, k, size, chunkSize, chunkSampleSize, resSize, sample_rate;
+    double *fft_res;
+    int m;
+    void *avc;
+
+    ppc->data = av_malloc(sizeof(double)*10000);
+
+    if (!ppc->data) {
+        av_log(avc, AV_LOG_ERROR, "Cann't allocate memmory for audio data\n");
+        return 0;
+    }
+
+    readAudio (&sample_rate, ppc);
+
+    size = ppc->nsamples;
+    m = log2(ppc->windowSize);
+    chunkSize = ppc->windowSize;
+    chunkSampleSize = size/chunkSize;
+    resSize = chunkSize * chunkSampleSize;
+
+    fft_res = av_malloc(sizeof(double) * resSize);
+
+    if (!fft_res) {
+        av_log(avc, AV_LOG_ERROR, "Cann't allocate memmory for storing fft data\n");
+        return 0;
+    }
+
+    RDFTContext *rdftC = av_rdft_init(m, DFT_R2C);
+    FFTSample *data;
+    data = av_malloc(sizeof(FFTSample)*chunkSize);
+
+    if (!data) {
+        av_log(avc, AV_LOG_ERROR, "Cann't allocate memmory for chunk fft data\n");
+        return 0;
+    }
+    // FFT transform for windowed time domain data
+    // window is of size chunkSize
+    k = 0;
+    while (k < resSize) {
+        //copy data
+        for (i = 0; i < chunkSize; i++) {
+            data[i] = ppc->data[i+k];
+        }
+        //calculate FFT
+        av_rdft_calc(rdftC, data);
+        for (i = 0; i < chunkSize; i++) {
+	    fft_res[i+k] = data[i];
+        }
+        k = k + chunkSize;
+    }
+
+    av_rdft_end(rdftC);
+    int pSize = resSize/chunkSize;
+    ppc->size = pSize;
+    ppc->peaks = av_malloc(sizeof(double)*pSize);
+
+    if (!ppc->peaks) {
+        av_log(avc, AV_LOG_ERROR, "Cann't allocate memory for peak storage\n");
+        return 0;
+    }
+
+    getPeakPointInChunk(chunkSize, fft_res, resSize, ppc->peaks);
+    return 1;
+}
+
+
+#define OFFSET(x) offsetof(PeakPointsContext, x)
+
+static const AVOption peakpoints_options[] = {
+    { "input",  "set input audio file", OFFSET(inputFile), AV_OPT_TYPE_STRING, {.str="sample.mp3"}, CHAR_MIN, CHAR_MAX },
+    { "wsize",  "set window size", OFFSET(windowSize),  AV_OPT_TYPE_INT,    {.i64=16},    0, INT_MAX},
+    { NULL },
+};
+
+static const char *peakpoints_get_name(void *ctx) {
+    return "peakpoints";
+}
+
+static const AVClass peakpoints_class = {
+    .class_name = "PeakPointsContext",
+    .item_name  = peakpoints_get_name,
+    .option     = peakpoints_options,
+};
+
+
+AVFILTER_DEFINE_CLASS(peakpoints);
+
+static av_cold int init(AVFilterContext *ctx)
+{
+    PeakPointsContext *p = ctx->priv;
+
+    if (!(p->inputFile)) {
+        av_log(ctx, AV_LOG_ERROR, "Input audio file must be passed\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (p->windowSize < 16) {
+	    av_log(ctx, AV_LOG_ERROR, "window size must be greater than or equal to 16\n");
+        return AVERROR(EINVAL);
+    }
+
+    // get peaks
+    int i;
+    if (getPeakPoints(p)) {
+        // print peaks
+        av_log(ctx, AV_LOG_INFO, "######## Peak points are ########\n");
+        for (i = 0; i < p->size; i++) {
+	        av_log(ctx, AV_LOG_INFO, "%f\n", p->peaks[i]);
+        }
+    } else {
+        av_log(ctx, AV_LOG_INFO, "Peak points not retrieved\n");
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    PeakPointsContext *p = ctx->priv;
+    int i;
+
+    if (p->data) {
+    	av_free(p->data);
+        p->data = NULL;
+    }
+
+    // free memory allocated for peaks
+    if (p->peaks) {
+        av_free(p->peaks);
+        p->peaks = NULL;
+    }
+}
+
+
+AVFilter ff_af_peakpoints = {
+    .name          = "peakpoints",
+    .description   = NULL_IF_CONFIG_SMALL("peak points from frequency domain windowed data."),
+    .init          = init,
+    .uninit        = uninit,
+    //.query_formats = query_formats,
+    .priv_size     = sizeof(PeakPointsContext),
+    //.inputs        = inputs,
+    //.outputs       = outputs,
+    .priv_class    = &peakpoints_class,
+};
-- 
1.9.1

