filter_audio.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. * copyright (c) 2013 Andrew Kelley
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file libavfilter audio filtering API usage example
  22. * @example filter_audio.c
  23. *
  24. * This example will generate a sine wave audio, pass it through a simple filter
  25. * chain, and then compute the MD5 checksum of the output data.
  26. *
  27. * The filter chain it uses is:
  28. * (input) -> abuffer -> volume -> aformat -> abuffersink -> (output)
  29. *
  30. * abuffer: This provides the endpoint where you can feed the decoded samples.
  31. * volume: In this example we hardcode it to 0.90.
  32. * aformat: This converts the samples to the samplefreq, channel layout,
  33. * and sample format required by the audio device.
  34. * abuffersink: This provides the endpoint where you can read the samples after
  35. * they have passed through the filter chain.
  36. */
  37. #include <inttypes.h>
  38. #include <math.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. #include <libavutil/channel_layout.h>
  42. #include <libavutil/md5.h>
  43. #include <libavutil/mem.h>
  44. #include <libavutil/opt.h>
  45. #include <libavutil/samplefmt.h>
  46. #include <libavfilter/avfilter.h>
  47. #include <libavfilter/buffersink.h>
  48. #include <libavfilter/buffersrc.h>
  49. #define INPUT_SAMPLERATE 48000
  50. #define INPUT_FORMAT AV_SAMPLE_FMT_FLTP
  51. #define INPUT_CHANNEL_LAYOUT (AVChannelLayout)AV_CHANNEL_LAYOUT_5POINT0
  52. #define VOLUME_VAL 0.90
  53. static int init_filter_graph(AVFilterGraph **graph, AVFilterContext **src,
  54. AVFilterContext **sink)
  55. {
  56. AVFilterGraph *filter_graph;
  57. AVFilterContext *abuffer_ctx;
  58. const AVFilter *abuffer;
  59. AVFilterContext *volume_ctx;
  60. const AVFilter *volume;
  61. AVFilterContext *aformat_ctx;
  62. const AVFilter *aformat;
  63. AVFilterContext *abuffersink_ctx;
  64. const AVFilter *abuffersink;
  65. AVDictionary *options_dict = NULL;
  66. uint8_t options_str[1024];
  67. uint8_t ch_layout[64];
  68. int err;
  69. /* Create a new filtergraph, which will contain all the filters. */
  70. filter_graph = avfilter_graph_alloc();
  71. if (!filter_graph) {
  72. fprintf(stderr, "Unable to create filter graph.\n");
  73. return AVERROR(ENOMEM);
  74. }
  75. /* Create the abuffer filter;
  76. * it will be used for feeding the data into the graph. */
  77. abuffer = avfilter_get_by_name("abuffer");
  78. if (!abuffer) {
  79. fprintf(stderr, "Could not find the abuffer filter.\n");
  80. return AVERROR_FILTER_NOT_FOUND;
  81. }
  82. abuffer_ctx = avfilter_graph_alloc_filter(filter_graph, abuffer, "src");
  83. if (!abuffer_ctx) {
  84. fprintf(stderr, "Could not allocate the abuffer instance.\n");
  85. return AVERROR(ENOMEM);
  86. }
  87. /* Set the filter options through the AVOptions API. */
  88. av_channel_layout_describe(&INPUT_CHANNEL_LAYOUT, ch_layout, sizeof(ch_layout));
  89. av_opt_set (abuffer_ctx, "channel_layout", ch_layout, AV_OPT_SEARCH_CHILDREN);
  90. av_opt_set (abuffer_ctx, "sample_fmt", av_get_sample_fmt_name(INPUT_FORMAT), AV_OPT_SEARCH_CHILDREN);
  91. av_opt_set_q (abuffer_ctx, "time_base", (AVRational){ 1, INPUT_SAMPLERATE }, AV_OPT_SEARCH_CHILDREN);
  92. av_opt_set_int(abuffer_ctx, "sample_rate", INPUT_SAMPLERATE, AV_OPT_SEARCH_CHILDREN);
  93. /* Now initialize the filter; we pass NULL options, since we have already
  94. * set all the options above. */
  95. err = avfilter_init_str(abuffer_ctx, NULL);
  96. if (err < 0) {
  97. fprintf(stderr, "Could not initialize the abuffer filter.\n");
  98. return err;
  99. }
  100. /* Create volume filter. */
  101. volume = avfilter_get_by_name("volume");
  102. if (!volume) {
  103. fprintf(stderr, "Could not find the volume filter.\n");
  104. return AVERROR_FILTER_NOT_FOUND;
  105. }
  106. volume_ctx = avfilter_graph_alloc_filter(filter_graph, volume, "volume");
  107. if (!volume_ctx) {
  108. fprintf(stderr, "Could not allocate the volume instance.\n");
  109. return AVERROR(ENOMEM);
  110. }
  111. /* A different way of passing the options is as key/value pairs in a
  112. * dictionary. */
  113. av_dict_set(&options_dict, "volume", AV_STRINGIFY(VOLUME_VAL), 0);
  114. err = avfilter_init_dict(volume_ctx, &options_dict);
  115. av_dict_free(&options_dict);
  116. if (err < 0) {
  117. fprintf(stderr, "Could not initialize the volume filter.\n");
  118. return err;
  119. }
  120. /* Create the aformat filter;
  121. * it ensures that the output is of the format we want. */
  122. aformat = avfilter_get_by_name("aformat");
  123. if (!aformat) {
  124. fprintf(stderr, "Could not find the aformat filter.\n");
  125. return AVERROR_FILTER_NOT_FOUND;
  126. }
  127. aformat_ctx = avfilter_graph_alloc_filter(filter_graph, aformat, "aformat");
  128. if (!aformat_ctx) {
  129. fprintf(stderr, "Could not allocate the aformat instance.\n");
  130. return AVERROR(ENOMEM);
  131. }
  132. /* A third way of passing the options is in a string of the form
  133. * key1=value1:key2=value2.... */
  134. snprintf(options_str, sizeof(options_str),
  135. "sample_fmts=%s:sample_rates=%d:channel_layouts=stereo",
  136. av_get_sample_fmt_name(AV_SAMPLE_FMT_S16), 44100);
  137. err = avfilter_init_str(aformat_ctx, options_str);
  138. if (err < 0) {
  139. av_log(NULL, AV_LOG_ERROR, "Could not initialize the aformat filter.\n");
  140. return err;
  141. }
  142. /* Finally create the abuffersink filter;
  143. * it will be used to get the filtered data out of the graph. */
  144. abuffersink = avfilter_get_by_name("abuffersink");
  145. if (!abuffersink) {
  146. fprintf(stderr, "Could not find the abuffersink filter.\n");
  147. return AVERROR_FILTER_NOT_FOUND;
  148. }
  149. abuffersink_ctx = avfilter_graph_alloc_filter(filter_graph, abuffersink, "sink");
  150. if (!abuffersink_ctx) {
  151. fprintf(stderr, "Could not allocate the abuffersink instance.\n");
  152. return AVERROR(ENOMEM);
  153. }
  154. /* This filter takes no options. */
  155. err = avfilter_init_str(abuffersink_ctx, NULL);
  156. if (err < 0) {
  157. fprintf(stderr, "Could not initialize the abuffersink instance.\n");
  158. return err;
  159. }
  160. /* Connect the filters;
  161. * in this simple case the filters just form a linear chain. */
  162. err = avfilter_link(abuffer_ctx, 0, volume_ctx, 0);
  163. if (err >= 0)
  164. err = avfilter_link(volume_ctx, 0, aformat_ctx, 0);
  165. if (err >= 0)
  166. err = avfilter_link(aformat_ctx, 0, abuffersink_ctx, 0);
  167. if (err < 0) {
  168. fprintf(stderr, "Error connecting filters\n");
  169. return err;
  170. }
  171. /* Configure the graph. */
  172. err = avfilter_graph_config(filter_graph, NULL);
  173. if (err < 0) {
  174. av_log(NULL, AV_LOG_ERROR, "Error configuring the filter graph\n");
  175. return err;
  176. }
  177. *graph = filter_graph;
  178. *src = abuffer_ctx;
  179. *sink = abuffersink_ctx;
  180. return 0;
  181. }
  182. /* Do something useful with the filtered data: this simple
  183. * example just prints the MD5 checksum of each plane to stdout. */
  184. static int process_output(struct AVMD5 *md5, AVFrame *frame)
  185. {
  186. int planar = av_sample_fmt_is_planar(frame->format);
  187. int channels = frame->ch_layout.nb_channels;
  188. int planes = planar ? channels : 1;
  189. int bps = av_get_bytes_per_sample(frame->format);
  190. int plane_size = bps * frame->nb_samples * (planar ? 1 : channels);
  191. int i, j;
  192. for (i = 0; i < planes; i++) {
  193. uint8_t checksum[16];
  194. av_md5_init(md5);
  195. av_md5_sum(checksum, frame->extended_data[i], plane_size);
  196. fprintf(stdout, "plane %d: 0x", i);
  197. for (j = 0; j < sizeof(checksum); j++)
  198. fprintf(stdout, "%02X", checksum[j]);
  199. fprintf(stdout, "\n");
  200. }
  201. fprintf(stdout, "\n");
  202. return 0;
  203. }
  204. /* Construct a frame of audio data to be filtered;
  205. * this simple example just synthesizes a sine wave. */
  206. static int get_input(AVFrame *frame, int frame_num)
  207. {
  208. int err, i, j;
  209. #define FRAME_SIZE 1024
  210. /* Set up the frame properties and allocate the buffer for the data. */
  211. frame->sample_rate = INPUT_SAMPLERATE;
  212. frame->format = INPUT_FORMAT;
  213. av_channel_layout_copy(&frame->ch_layout, &INPUT_CHANNEL_LAYOUT);
  214. frame->nb_samples = FRAME_SIZE;
  215. frame->pts = frame_num * FRAME_SIZE;
  216. err = av_frame_get_buffer(frame, 0);
  217. if (err < 0)
  218. return err;
  219. /* Fill the data for each channel. */
  220. for (i = 0; i < 5; i++) {
  221. float *data = (float*)frame->extended_data[i];
  222. for (j = 0; j < frame->nb_samples; j++)
  223. data[j] = sin(2 * M_PI * (frame_num + j) * (i + 1) / FRAME_SIZE);
  224. }
  225. return 0;
  226. }
  227. int main(int argc, char *argv[])
  228. {
  229. struct AVMD5 *md5;
  230. AVFilterGraph *graph;
  231. AVFilterContext *src, *sink;
  232. AVFrame *frame;
  233. uint8_t errstr[1024];
  234. float duration;
  235. int err, nb_frames, i;
  236. if (argc < 2) {
  237. fprintf(stderr, "Usage: %s <duration>\n", argv[0]);
  238. return 1;
  239. }
  240. duration = atof(argv[1]);
  241. nb_frames = duration * INPUT_SAMPLERATE / FRAME_SIZE;
  242. if (nb_frames <= 0) {
  243. fprintf(stderr, "Invalid duration: %s\n", argv[1]);
  244. return 1;
  245. }
  246. /* Allocate the frame we will be using to store the data. */
  247. frame = av_frame_alloc();
  248. if (!frame) {
  249. fprintf(stderr, "Error allocating the frame\n");
  250. return 1;
  251. }
  252. md5 = av_md5_alloc();
  253. if (!md5) {
  254. fprintf(stderr, "Error allocating the MD5 context\n");
  255. return 1;
  256. }
  257. /* Set up the filtergraph. */
  258. err = init_filter_graph(&graph, &src, &sink);
  259. if (err < 0) {
  260. fprintf(stderr, "Unable to init filter graph:");
  261. goto fail;
  262. }
  263. /* the main filtering loop */
  264. for (i = 0; i < nb_frames; i++) {
  265. /* get an input frame to be filtered */
  266. err = get_input(frame, i);
  267. if (err < 0) {
  268. fprintf(stderr, "Error generating input frame:");
  269. goto fail;
  270. }
  271. /* Send the frame to the input of the filtergraph. */
  272. err = av_buffersrc_add_frame(src, frame);
  273. if (err < 0) {
  274. av_frame_unref(frame);
  275. fprintf(stderr, "Error submitting the frame to the filtergraph:");
  276. goto fail;
  277. }
  278. /* Get all the filtered output that is available. */
  279. while ((err = av_buffersink_get_frame(sink, frame)) >= 0) {
  280. /* now do something with our filtered frame */
  281. err = process_output(md5, frame);
  282. if (err < 0) {
  283. fprintf(stderr, "Error processing the filtered frame:");
  284. goto fail;
  285. }
  286. av_frame_unref(frame);
  287. }
  288. if (err == AVERROR(EAGAIN)) {
  289. /* Need to feed more frames in. */
  290. continue;
  291. } else if (err == AVERROR_EOF) {
  292. /* Nothing more to do, finish. */
  293. break;
  294. } else if (err < 0) {
  295. /* An error occurred. */
  296. fprintf(stderr, "Error filtering the data:");
  297. goto fail;
  298. }
  299. }
  300. avfilter_graph_free(&graph);
  301. av_frame_free(&frame);
  302. av_freep(&md5);
  303. return 0;
  304. fail:
  305. av_strerror(err, errstr, sizeof(errstr));
  306. fprintf(stderr, "%s\n", errstr);
  307. return 1;
  308. }