filtering_video.c 9.3 KB

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