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