filtering_video.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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/buffersink.h>
  33. #include <libavfilter/buffersrc.h>
  34. #include <libavutil/opt.h>
  35. const char *filter_descr = "scale=78:24,transpose=cclock";
  36. /* other way:
  37. scale=78:24 [scl]; [scl] transpose=cclock // assumes "[in]" and "[out]" to be input output pads respectively
  38. */
  39. static AVFormatContext *fmt_ctx;
  40. static AVCodecContext *dec_ctx;
  41. AVFilterContext *buffersink_ctx;
  42. AVFilterContext *buffersrc_ctx;
  43. AVFilterGraph *filter_graph;
  44. static int video_stream_index = -1;
  45. static int64_t last_pts = AV_NOPTS_VALUE;
  46. static int open_input_file(const char *filename)
  47. {
  48. int ret;
  49. AVCodec *dec;
  50. if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
  51. av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
  52. return ret;
  53. }
  54. if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  55. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  56. return ret;
  57. }
  58. /* select the video stream */
  59. ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
  60. if (ret < 0) {
  61. av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
  62. return ret;
  63. }
  64. video_stream_index = ret;
  65. /* create decoding context */
  66. dec_ctx = avcodec_alloc_context3(dec);
  67. if (!dec_ctx)
  68. return AVERROR(ENOMEM);
  69. avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);
  70. av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0);
  71. /* init the video decoder */
  72. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  73. av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
  74. return ret;
  75. }
  76. return 0;
  77. }
  78. static int init_filters(const char *filters_descr)
  79. {
  80. char args[512];
  81. int ret = 0;
  82. const AVFilter *buffersrc = avfilter_get_by_name("buffer");
  83. const AVFilter *buffersink = avfilter_get_by_name("buffersink");
  84. AVFilterInOut *outputs = avfilter_inout_alloc();
  85. AVFilterInOut *inputs = avfilter_inout_alloc();
  86. AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base;
  87. enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };
  88. filter_graph = avfilter_graph_alloc();
  89. if (!outputs || !inputs || !filter_graph) {
  90. ret = AVERROR(ENOMEM);
  91. goto end;
  92. }
  93. /* buffer video source: the decoded frames from the decoder will be inserted here. */
  94. snprintf(args, sizeof(args),
  95. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  96. dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
  97. time_base.num, time_base.den,
  98. dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
  99. ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
  100. args, NULL, filter_graph);
  101. if (ret < 0) {
  102. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
  103. goto end;
  104. }
  105. /* buffer video sink: to terminate the filter chain. */
  106. ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
  107. NULL, NULL, filter_graph);
  108. if (ret < 0) {
  109. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
  110. goto end;
  111. }
  112. ret = av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,
  113. AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
  114. if (ret < 0) {
  115. av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
  116. goto end;
  117. }
  118. /*
  119. * Set the endpoints for the filter graph. The filter_graph will
  120. * be linked to the graph described by filters_descr.
  121. */
  122. /*
  123. * The buffer source output must be connected to the input pad of
  124. * the first filter described by filters_descr; since the first
  125. * filter input label is not specified, it is set to "in" by
  126. * default.
  127. */
  128. outputs->name = av_strdup("in");
  129. outputs->filter_ctx = buffersrc_ctx;
  130. outputs->pad_idx = 0;
  131. outputs->next = NULL;
  132. /*
  133. * The buffer sink input must be connected to the output pad of
  134. * the last filter described by filters_descr; since the last
  135. * filter output label is not specified, it is set to "out" by
  136. * default.
  137. */
  138. inputs->name = av_strdup("out");
  139. inputs->filter_ctx = buffersink_ctx;
  140. inputs->pad_idx = 0;
  141. inputs->next = NULL;
  142. if ((ret = avfilter_graph_parse_ptr(filter_graph, filters_descr,
  143. &inputs, &outputs, NULL)) < 0)
  144. goto end;
  145. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
  146. goto end;
  147. end:
  148. avfilter_inout_free(&inputs);
  149. avfilter_inout_free(&outputs);
  150. return ret;
  151. }
  152. static void display_frame(const AVFrame *frame, AVRational time_base)
  153. {
  154. int x, y;
  155. uint8_t *p0, *p;
  156. int64_t delay;
  157. if (frame->pts != AV_NOPTS_VALUE) {
  158. if (last_pts != AV_NOPTS_VALUE) {
  159. /* sleep roughly the right amount of time;
  160. * usleep is in microseconds, just like AV_TIME_BASE. */
  161. delay = av_rescale_q(frame->pts - last_pts,
  162. time_base, AV_TIME_BASE_Q);
  163. if (delay > 0 && delay < 1000000)
  164. usleep(delay);
  165. }
  166. last_pts = frame->pts;
  167. }
  168. /* Trivial ASCII grayscale display. */
  169. p0 = frame->data[0];
  170. puts("\033c");
  171. for (y = 0; y < frame->height; y++) {
  172. p = p0;
  173. for (x = 0; x < frame->width; x++)
  174. putchar(" .-+#"[*(p++) / 52]);
  175. putchar('\n');
  176. p0 += frame->linesize[0];
  177. }
  178. fflush(stdout);
  179. }
  180. int main(int argc, char **argv)
  181. {
  182. int ret;
  183. AVPacket packet;
  184. AVFrame *frame = av_frame_alloc();
  185. AVFrame *filt_frame = av_frame_alloc();
  186. if (!frame || !filt_frame) {
  187. perror("Could not allocate frame");
  188. exit(1);
  189. }
  190. if (argc != 2) {
  191. fprintf(stderr, "Usage: %s file\n", argv[0]);
  192. exit(1);
  193. }
  194. if ((ret = open_input_file(argv[1])) < 0)
  195. goto end;
  196. if ((ret = init_filters(filter_descr)) < 0)
  197. goto end;
  198. /* read all packets */
  199. while (1) {
  200. if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
  201. break;
  202. if (packet.stream_index == video_stream_index) {
  203. ret = avcodec_send_packet(dec_ctx, &packet);
  204. if (ret < 0) {
  205. av_log(NULL, AV_LOG_ERROR, "Error while sending a packet to the decoder\n");
  206. break;
  207. }
  208. while (ret >= 0) {
  209. ret = avcodec_receive_frame(dec_ctx, frame);
  210. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  211. break;
  212. } else if (ret < 0) {
  213. av_log(NULL, AV_LOG_ERROR, "Error while receiving a frame from the decoder\n");
  214. goto end;
  215. }
  216. if (ret >= 0) {
  217. frame->pts = frame->best_effort_timestamp;
  218. /* push the decoded frame into the filtergraph */
  219. if (av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0) {
  220. av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
  221. break;
  222. }
  223. /* pull filtered frames from the filtergraph */
  224. while (1) {
  225. ret = av_buffersink_get_frame(buffersink_ctx, filt_frame);
  226. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  227. break;
  228. if (ret < 0)
  229. goto end;
  230. display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
  231. av_frame_unref(filt_frame);
  232. }
  233. av_frame_unref(frame);
  234. }
  235. }
  236. }
  237. av_packet_unref(&packet);
  238. }
  239. end:
  240. avfilter_graph_free(&filter_graph);
  241. avcodec_free_context(&dec_ctx);
  242. avformat_close_input(&fmt_ctx);
  243. av_frame_free(&frame);
  244. av_frame_free(&filt_frame);
  245. if (ret < 0 && ret != AVERROR_EOF) {
  246. fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
  247. exit(1);
  248. }
  249. exit(0);
  250. }