]> git.sesse.net Git - ffmpeg/blob - doc/examples/filtering.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / doc / examples / filtering.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  */
28
29 #define _XOPEN_SOURCE 600 /* for usleep */
30
31 #include <libavcodec/avcodec.h>
32 #include <libavformat/avformat.h>
33 #include <libavfilter/avfiltergraph.h>
34 #include <libavfilter/vsrc_buffer.h>
35
36 const char *filter_descr = "scale=78:24";
37
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
46 static int open_input_file(const char *filename)
47 {
48     int ret, i;
49     AVCodec *dec;
50
51     if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
52         av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
53         return ret;
54     }
55
56     if ((ret = av_find_stream_info(fmt_ctx)) < 0) {
57         av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
58         return ret;
59     }
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     dec_ctx = fmt_ctx->streams[video_stream_index]->codec;
69
70     /* init the video decoder */
71     if ((ret = avcodec_open(dec_ctx, dec)) < 0) {
72         av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
73         return ret;
74     }
75
76     return 0;
77 }
78
79 static int init_filters(const char *filters_descr)
80 {
81     char args[512];
82     int ret;
83     AVFilter *buffersrc  = avfilter_get_by_name("buffer");
84     AVFilter *buffersink = avfilter_get_by_name("buffersink");
85     AVFilterInOut *outputs = avfilter_inout_alloc();
86     AVFilterInOut *inputs  = avfilter_inout_alloc();
87     enum PixelFormat pix_fmts[] = { PIX_FMT_GRAY8, PIX_FMT_NONE };
88     filter_graph = avfilter_graph_alloc();
89
90     /* buffer video source: the decoded frames from the decoder will be inserted here. */
91     snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d",
92              dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
93              dec_ctx->time_base.num, dec_ctx->time_base.den,
94              dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
95     ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
96                                        args, NULL, filter_graph);
97     if (ret < 0) {
98         av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
99         return ret;
100     }
101
102     /* buffer video sink: to terminate the filter chain. */
103     ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
104                                        NULL, pix_fmts, filter_graph);
105     if (ret < 0) {
106         av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
107         return ret;
108     }
109
110     /* Endpoints for the filter graph. */
111     outputs->name       = av_strdup("in");
112     outputs->filter_ctx = buffersrc_ctx;
113     outputs->pad_idx    = 0;
114     outputs->next       = NULL;
115
116     inputs->name       = av_strdup("out");
117     inputs->filter_ctx = buffersink_ctx;
118     inputs->pad_idx    = 0;
119     inputs->next       = NULL;
120
121     if ((ret = avfilter_graph_parse(filter_graph, filter_descr,
122                                     &inputs, &outputs, NULL)) < 0)
123         return ret;
124
125     if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
126         return ret;
127 }
128
129 static void display_picref(AVFilterBufferRef *picref, AVRational time_base)
130 {
131     int x, y;
132     uint8_t *p0, *p;
133     int64_t delay;
134
135     if (picref->pts != AV_NOPTS_VALUE) {
136         if (last_pts != AV_NOPTS_VALUE) {
137             /* sleep roughly the right amount of time;
138              * usleep is in microseconds, just like AV_TIME_BASE. */
139             delay = av_rescale_q(picref->pts - last_pts,
140                                  time_base, AV_TIME_BASE_Q);
141             if (delay > 0 && delay < 1000000)
142                 usleep(delay);
143         }
144         last_pts = picref->pts;
145     }
146
147     /* Trivial ASCII grayscale display. */
148     p0 = picref->data[0];
149     puts("\033c");
150     for (y = 0; y < picref->video->h; y++) {
151         p = p0;
152         for (x = 0; x < picref->video->w; x++)
153             putchar(" .-+#"[*(p++) / 52]);
154         putchar('\n');
155         p0 += picref->linesize[0];
156     }
157     fflush(stdout);
158 }
159
160 int main(int argc, char **argv)
161 {
162     int ret;
163     AVPacket packet;
164     AVFrame frame;
165     int got_frame;
166
167     if (argc != 2) {
168         fprintf(stderr, "Usage: %s file\n", argv[0]);
169         exit(1);
170     }
171
172     avcodec_register_all();
173     av_register_all();
174     avfilter_register_all();
175
176     if ((ret = open_input_file(argv[1]) < 0))
177         goto end;
178     if ((ret = init_filters(filter_descr)) < 0)
179         goto end;
180
181     /* read all packets */
182     while (1) {
183         AVFilterBufferRef *picref;
184         if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
185             break;
186
187         if (packet.stream_index == video_stream_index) {
188             avcodec_get_frame_defaults(&frame);
189             got_frame = 0;
190             ret = avcodec_decode_video2(dec_ctx, &frame, &got_frame, &packet);
191             av_free_packet(&packet);
192             if (ret < 0) {
193                 av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
194                 break;
195             }
196
197             if (got_frame) {
198                 if (frame.pts == AV_NOPTS_VALUE)
199                     frame.pts = frame.pkt_dts == AV_NOPTS_VALUE ?
200                         frame.pkt_dts : frame.pkt_pts;
201                 /* push the decoded frame into the filtergraph */
202                 av_vsrc_buffer_add_frame(buffersrc_ctx, &frame);
203
204                 /* pull filtered pictures from the filtergraph */
205                 while (avfilter_poll_frame(buffersink_ctx->inputs[0])) {
206                     av_vsink_buffer_get_video_buffer_ref(buffersink_ctx, &picref, 0);
207                     if (picref) {
208                         display_picref(picref, buffersink_ctx->inputs[0]->time_base);
209                         avfilter_unref_buffer(picref);
210                     }
211                 }
212             }
213         }
214     }
215 end:
216     avfilter_graph_free(&filter_graph);
217     if (dec_ctx)
218         avcodec_close(dec_ctx);
219     av_close_input_file(fmt_ctx);
220
221     if (ret < 0 && ret != AVERROR_EOF) {
222         char buf[1024];
223         av_strerror(ret, buf, sizeof(buf));
224         fprintf(stderr, "Error occurred: %s\n", buf);
225         exit(1);
226     }
227
228     exit(0);
229 }