filter_audio.c 12 KB

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