decode_filter_video.c 10 KB

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