filtering_video.c 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * Copyright (c) 2010 Nicolas George
  3. * Copyright (c) 2011 Stefano Sabatini
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. */
  23. /**
  24. * @file
  25. * API example for decoding and filtering
  26. * @example filtering_video.c
  27. */
  28. #define _XOPEN_SOURCE 600 /* for usleep */
  29. #include <unistd.h>
  30. #include <libavcodec/avcodec.h>
  31. #include <libavformat/avformat.h>
  32. #include <libavfilter/avfiltergraph.h>
  33. #include <libavfilter/avcodec.h>
  34. #include <libavfilter/buffersink.h>
  35. #include <libavfilter/buffersrc.h>
  36. #include <libavutil/opt.h>
  37. const char *filter_descr = "scale=78:24";
  38. static AVFormatContext *fmt_ctx;
  39. static AVCodecContext *dec_ctx;
  40. AVFilterContext *buffersink_ctx;
  41. AVFilterContext *buffersrc_ctx;
  42. AVFilterGraph *filter_graph;
  43. static int video_stream_index = -1;
  44. static int64_t last_pts = AV_NOPTS_VALUE;
  45. static int open_input_file(const char *filename)
  46. {
  47. int ret;
  48. AVCodec *dec;
  49. if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
  50. av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
  51. return ret;
  52. }
  53. if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  54. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  55. return ret;
  56. }
  57. /* select the video stream */
  58. ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
  59. if (ret < 0) {
  60. av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
  61. return ret;
  62. }
  63. video_stream_index = ret;
  64. dec_ctx = fmt_ctx->streams[video_stream_index]->codec;
  65. av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0);
  66. /* init the video decoder */
  67. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  68. av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
  69. return ret;
  70. }
  71. return 0;
  72. }
  73. static int init_filters(const char *filters_descr)
  74. {
  75. char args[512];
  76. int ret = 0;
  77. AVFilter *buffersrc = avfilter_get_by_name("buffer");
  78. AVFilter *buffersink = avfilter_get_by_name("buffersink");
  79. AVFilterInOut *outputs = avfilter_inout_alloc();
  80. AVFilterInOut *inputs = avfilter_inout_alloc();
  81. enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };
  82. filter_graph = avfilter_graph_alloc();
  83. if (!outputs || !inputs || !filter_graph) {
  84. ret = AVERROR(ENOMEM);
  85. goto end;
  86. }
  87. /* buffer video source: the decoded frames from the decoder will be inserted here. */
  88. snprintf(args, sizeof(args),
  89. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  90. dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
  91. dec_ctx->time_base.num, dec_ctx->time_base.den,
  92. dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
  93. ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
  94. args, NULL, filter_graph);
  95. if (ret < 0) {
  96. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
  97. goto end;
  98. }
  99. /* buffer video sink: to terminate the filter chain. */
  100. ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
  101. NULL, NULL, filter_graph);
  102. if (ret < 0) {
  103. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
  104. goto end;
  105. }
  106. ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,
  107. AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
  108. if (ret < 0) {
  109. av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
  110. goto end;
  111. }
  112. /* Endpoints for the filter graph. */
  113. outputs->name = av_strdup("in");
  114. outputs->filter_ctx = buffersrc_ctx;
  115. outputs->pad_idx = 0;
  116. outputs->next = NULL;
  117. inputs->name = av_strdup("out");
  118. inputs->filter_ctx = buffersink_ctx;
  119. inputs->pad_idx = 0;
  120. inputs->next = NULL;
  121. if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
  122. &inputs, &outputs, NULL)) < 0)
  123. goto end;
  124. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
  125. goto end;
  126. end:
  127. avfilter_inout_free(&inputs);
  128. avfilter_inout_free(&outputs);
  129. return ret;
  130. }
  131. static void display_frame(const AVFrame *frame, AVRational time_base)
  132. {
  133. int x, y;
  134. uint8_t *p0, *p;
  135. int64_t delay;
  136. if (frame->pts != AV_NOPTS_VALUE) {
  137. if (last_pts != AV_NOPTS_VALUE) {
  138. /* sleep roughly the right amount of time;
  139. * usleep is in microseconds, just like AV_TIME_BASE. */
  140. delay = av_rescale_q(frame->pts - last_pts,
  141. time_base, AV_TIME_BASE_Q);
  142. if (delay > 0 && delay < 1000000)
  143. usleep(delay);
  144. }
  145. last_pts = frame->pts;
  146. }
  147. /* Trivial ASCII grayscale display. */
  148. p0 = frame->data[0];
  149. puts("\033c");
  150. for (y = 0; y < frame->height; y++) {
  151. p = p0;
  152. for (x = 0; x < frame->width; x++)
  153. putchar(" .-+#"[*(p++) / 52]);
  154. putchar('\n');
  155. p0 += frame->linesize[0];
  156. }
  157. fflush(stdout);
  158. }
  159. int main(int argc, char **argv)
  160. {
  161. int ret;
  162. AVPacket packet;
  163. AVFrame *frame = av_frame_alloc();
  164. AVFrame *filt_frame = av_frame_alloc();
  165. int got_frame;
  166. if (!frame || !filt_frame) {
  167. perror("Could not allocate frame");
  168. exit(1);
  169. }
  170. if (argc != 2) {
  171. fprintf(stderr, "Usage: %s file\n", argv[0]);
  172. exit(1);
  173. }
  174. av_register_all();
  175. avfilter_register_all();
  176. if ((ret = open_input_file(argv[1])) < 0)
  177. goto end;
  178. if ((ret = init_filters(filter_descr)) < 0)
  179. goto end;
  180. /* read all packets */
  181. while (1) {
  182. if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
  183. break;
  184. if (packet.stream_index == video_stream_index) {
  185. got_frame = 0;
  186. ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet);
  187. if (ret < 0) {
  188. av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
  189. break;
  190. }
  191. if (got_frame) {
  192. frame->pts = av_frame_get_best_effort_timestamp(frame);
  193. /* push the decoded frame into the filtergraph */
  194. if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
  195. av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
  196. break;
  197. }
  198. /* pull filtered frames from the filtergraph */
  199. while (1) {
  200. ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
  201. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  202. break;
  203. if (ret < 0)
  204. goto end;
  205. display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
  206. av_frame_unref(filt_frame);
  207. }
  208. av_frame_unref(frame);
  209. }
  210. }
  211. av_free_packet(&packet);
  212. }
  213. end:
  214. avfilter_graph_free(&filter_graph);
  215. avcodec_close(dec_ctx);
  216. avformat_close_input(&fmt_ctx);
  217. av_frame_free(&frame);
  218. av_frame_free(&filt_frame);
  219. if (ret < 0 && ret != AVERROR_EOF) {
  220. fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
  221. exit(1);
  222. }
  223. exit(0);
  224. }