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