avprobe: allow showing only one container/stream property.
[platform/upstream/libav.git] / avprobe.c
1 /*
2  * avprobe : Simple Media Prober based on the Libav libraries
3  * Copyright (c) 2007-2010 Stefano Sabatini
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include "libavformat/avformat.h"
25 #include "libavcodec/avcodec.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/pixdesc.h"
28 #include "libavutil/dict.h"
29 #include "libavdevice/avdevice.h"
30 #include "cmdutils.h"
31
32 const char program_name[] = "avprobe";
33 const int program_birth_year = 2007;
34
35 static int do_show_format  = 0;
36 static AVDictionary *fmt_entries_to_show = NULL;
37 static int do_show_packets = 0;
38 static int do_show_streams = 0;
39
40 static int show_value_unit              = 0;
41 static int use_value_prefix             = 0;
42 static int use_byte_value_binary_prefix = 0;
43 static int use_value_sexagesimal_format = 0;
44
45 /* globals */
46 static const OptionDef options[];
47
48 /* AVprobe context */
49 static const char *input_filename;
50 static AVInputFormat *iformat = NULL;
51
52 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
53 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
54
55 static const char unit_second_str[]         = "s"    ;
56 static const char unit_hertz_str[]          = "Hz"   ;
57 static const char unit_byte_str[]           = "byte" ;
58 static const char unit_bit_per_second_str[] = "bit/s";
59
60 void exit_program(int ret)
61 {
62     av_dict_free(&fmt_entries_to_show);
63     exit(ret);
64 }
65
66 static char *value_string(char *buf, int buf_size, double val, const char *unit)
67 {
68     if (unit == unit_second_str && use_value_sexagesimal_format) {
69         double secs;
70         int hours, mins;
71         secs  = val;
72         mins  = (int)secs / 60;
73         secs  = secs - mins * 60;
74         hours = mins / 60;
75         mins %= 60;
76         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
77     } else if (use_value_prefix) {
78         const char *prefix_string;
79         int index;
80
81         if (unit == unit_byte_str && use_byte_value_binary_prefix) {
82             index = (int) (log(val)/log(2)) / 10;
83             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
84             val  /= pow(2, index * 10);
85             prefix_string = binary_unit_prefixes[index];
86         } else {
87             index = (int) (log10(val)) / 3;
88             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
89             val  /= pow(10, index * 3);
90             prefix_string = decimal_unit_prefixes[index];
91         }
92
93         snprintf(buf, buf_size, "%.3f %s%s", val, prefix_string,
94                  show_value_unit ? unit : "");
95     } else {
96         snprintf(buf, buf_size, "%f %s", val, show_value_unit ? unit : "");
97     }
98
99     return buf;
100 }
101
102 static char *time_value_string(char *buf, int buf_size, int64_t val,
103                                const AVRational *time_base)
104 {
105     if (val == AV_NOPTS_VALUE) {
106         snprintf(buf, buf_size, "N/A");
107     } else {
108         value_string(buf, buf_size, val * av_q2d(*time_base), unit_second_str);
109     }
110
111     return buf;
112 }
113
114 static char *ts_value_string (char *buf, int buf_size, int64_t ts)
115 {
116     if (ts == AV_NOPTS_VALUE) {
117         snprintf(buf, buf_size, "N/A");
118     } else {
119         snprintf(buf, buf_size, "%"PRId64, ts);
120     }
121
122     return buf;
123 }
124
125 static const char *media_type_string(enum AVMediaType media_type)
126 {
127     switch (media_type) {
128     case AVMEDIA_TYPE_VIDEO:      return "video";
129     case AVMEDIA_TYPE_AUDIO:      return "audio";
130     case AVMEDIA_TYPE_DATA:       return "data";
131     case AVMEDIA_TYPE_SUBTITLE:   return "subtitle";
132     case AVMEDIA_TYPE_ATTACHMENT: return "attachment";
133     default:                      return "unknown";
134     }
135 }
136
137 static void show_packet(AVFormatContext *fmt_ctx, AVPacket *pkt)
138 {
139     char val_str[128];
140     AVStream *st = fmt_ctx->streams[pkt->stream_index];
141
142     printf("[PACKET]\n");
143     printf("codec_type=%s\n", media_type_string(st->codec->codec_type));
144     printf("stream_index=%d\n", pkt->stream_index);
145     printf("pts=%s\n", ts_value_string(val_str, sizeof(val_str), pkt->pts));
146     printf("pts_time=%s\n", time_value_string(val_str, sizeof(val_str),
147                                               pkt->pts, &st->time_base));
148     printf("dts=%s\n", ts_value_string(val_str, sizeof(val_str), pkt->dts));
149     printf("dts_time=%s\n", time_value_string(val_str, sizeof(val_str),
150                                               pkt->dts, &st->time_base));
151     printf("duration=%s\n", ts_value_string(val_str, sizeof(val_str),
152                                             pkt->duration));
153     printf("duration_time=%s\n", time_value_string(val_str, sizeof(val_str),
154                                                    pkt->duration,
155                                                    &st->time_base));
156     printf("size=%s\n", value_string(val_str, sizeof(val_str),
157                                      pkt->size, unit_byte_str));
158     printf("pos=%"PRId64"\n", pkt->pos);
159     printf("flags=%c\n", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
160     printf("[/PACKET]\n");
161 }
162
163 static void show_packets(AVFormatContext *fmt_ctx)
164 {
165     AVPacket pkt;
166
167     av_init_packet(&pkt);
168
169     while (!av_read_frame(fmt_ctx, &pkt))
170         show_packet(fmt_ctx, &pkt);
171 }
172
173 static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)
174 {
175     AVStream *stream = fmt_ctx->streams[stream_idx];
176     AVCodecContext *dec_ctx;
177     AVCodec *dec;
178     char val_str[128];
179     AVDictionaryEntry *tag = NULL;
180     AVRational display_aspect_ratio;
181
182     printf("[STREAM]\n");
183
184     printf("index=%d\n", stream->index);
185
186     if ((dec_ctx = stream->codec)) {
187         if ((dec = dec_ctx->codec)) {
188             printf("codec_name=%s\n", dec->name);
189             printf("codec_long_name=%s\n", dec->long_name);
190         } else {
191             printf("codec_name=unknown\n");
192         }
193
194         printf("codec_type=%s\n", media_type_string(dec_ctx->codec_type));
195         printf("codec_time_base=%d/%d\n",
196                dec_ctx->time_base.num, dec_ctx->time_base.den);
197
198         /* print AVI/FourCC tag */
199         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
200         printf("codec_tag_string=%s\n", val_str);
201         printf("codec_tag=0x%04x\n", dec_ctx->codec_tag);
202
203         switch (dec_ctx->codec_type) {
204         case AVMEDIA_TYPE_VIDEO:
205             printf("width=%d\n", dec_ctx->width);
206             printf("height=%d\n", dec_ctx->height);
207             printf("has_b_frames=%d\n", dec_ctx->has_b_frames);
208             if (dec_ctx->sample_aspect_ratio.num) {
209                 printf("sample_aspect_ratio=%d:%d\n",
210                        dec_ctx->sample_aspect_ratio.num,
211                        dec_ctx->sample_aspect_ratio.den);
212                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
213                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
214                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
215                           1024*1024);
216                 printf("display_aspect_ratio=%d:%d\n",
217                        display_aspect_ratio.num, display_aspect_ratio.den);
218             }
219             printf("pix_fmt=%s\n",
220                    dec_ctx->pix_fmt != PIX_FMT_NONE ? av_pix_fmt_descriptors[dec_ctx->pix_fmt].name
221                                                     : "unknown");
222             printf("level=%d\n", dec_ctx->level);
223             break;
224
225         case AVMEDIA_TYPE_AUDIO:
226             printf("sample_rate=%s\n", value_string(val_str, sizeof(val_str),
227                                                     dec_ctx->sample_rate,
228                                                     unit_hertz_str));
229             printf("channels=%d\n", dec_ctx->channels);
230             printf("bits_per_sample=%d\n",
231                    av_get_bits_per_sample(dec_ctx->codec_id));
232             break;
233         }
234     } else {
235         printf("codec_type=unknown\n");
236     }
237
238     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
239         printf("id=0x%x\n", stream->id);
240     printf("r_frame_rate=%d/%d\n",
241            stream->r_frame_rate.num, stream->r_frame_rate.den);
242     printf("avg_frame_rate=%d/%d\n",
243            stream->avg_frame_rate.num, stream->avg_frame_rate.den);
244     printf("time_base=%d/%d\n",
245            stream->time_base.num, stream->time_base.den);
246     printf("start_time=%s\n",
247            time_value_string(val_str, sizeof(val_str),
248                              stream->start_time, &stream->time_base));
249     printf("duration=%s\n",
250            time_value_string(val_str, sizeof(val_str),
251                              stream->duration, &stream->time_base));
252     if (stream->nb_frames)
253         printf("nb_frames=%"PRId64"\n", stream->nb_frames);
254
255     while ((tag = av_dict_get(stream->metadata, "", tag,
256                               AV_DICT_IGNORE_SUFFIX)))
257         printf("TAG:%s=%s\n", tag->key, tag->value);
258
259     printf("[/STREAM]\n");
260 }
261
262 static void print_format_entry(const char *tag,
263                                const char *val)
264 {
265     if (!fmt_entries_to_show) {
266         if (tag) {
267             printf("%s=%s\n", tag, val);
268         } else {
269             printf("%s\n", val);
270         }
271     } else if (tag && av_dict_get(fmt_entries_to_show, tag, NULL, 0)) {
272         printf("%s=%s\n", tag, val);
273     }
274 }
275
276 static void show_format(AVFormatContext *fmt_ctx)
277 {
278     AVDictionaryEntry *tag = NULL;
279     char val_str[128];
280     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
281
282     print_format_entry(NULL, "[FORMAT]");
283     print_format_entry("filename",         fmt_ctx->filename);
284     snprintf(val_str, sizeof(val_str) - 1, "%d", fmt_ctx->nb_streams);
285     print_format_entry("nb_streams",       val_str);
286     print_format_entry("format_name",      fmt_ctx->iformat->name);
287     print_format_entry("format_long_name", fmt_ctx->iformat->long_name);
288     print_format_entry("start_time",
289                        time_value_string(val_str, sizeof(val_str),
290                                          fmt_ctx->start_time, &AV_TIME_BASE_Q));
291     print_format_entry("duration",
292                        time_value_string(val_str, sizeof(val_str),
293                                          fmt_ctx->duration, &AV_TIME_BASE_Q));
294     print_format_entry("size",
295                        size >= 0 ? value_string(val_str, sizeof(val_str),
296                                                 size, unit_byte_str)
297                                   : "unknown");
298     print_format_entry("bit_rate",
299                        value_string(val_str, sizeof(val_str),
300                                     fmt_ctx->bit_rate, unit_bit_per_second_str));
301
302     while ((tag = av_dict_get(fmt_ctx->metadata, "", tag,
303                               AV_DICT_IGNORE_SUFFIX))) {
304         snprintf(val_str, sizeof(val_str) - 1, "TAG:%s", tag->key);
305         print_format_entry(val_str, tag->value);
306     }
307
308     print_format_entry(NULL, "[/FORMAT]");
309 }
310
311 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
312 {
313     int err, i;
314     AVFormatContext *fmt_ctx = NULL;
315     AVDictionaryEntry *t;
316
317     if ((err = avformat_open_input(&fmt_ctx, filename,
318                                    iformat, &format_opts)) < 0) {
319         print_error(filename, err);
320         return err;
321     }
322     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
323         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
324         return AVERROR_OPTION_NOT_FOUND;
325     }
326
327
328     /* fill the streams in the format context */
329     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
330         print_error(filename, err);
331         return err;
332     }
333
334     av_dump_format(fmt_ctx, 0, filename, 0);
335
336     /* bind a decoder to each input stream */
337     for (i = 0; i < fmt_ctx->nb_streams; i++) {
338         AVStream *stream = fmt_ctx->streams[i];
339         AVCodec *codec;
340
341         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
342             fprintf(stderr,
343                     "Unsupported codec with id %d for input stream %d\n",
344                     stream->codec->codec_id, stream->index);
345         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
346             fprintf(stderr, "Error while opening codec for input stream %d\n",
347                     stream->index);
348         }
349     }
350
351     *fmt_ctx_ptr = fmt_ctx;
352     return 0;
353 }
354
355 static int probe_file(const char *filename)
356 {
357     AVFormatContext *fmt_ctx;
358     int ret, i;
359
360     if ((ret = open_input_file(&fmt_ctx, filename)))
361         return ret;
362
363     if (do_show_packets)
364         show_packets(fmt_ctx);
365
366     if (do_show_streams)
367         for (i = 0; i < fmt_ctx->nb_streams; i++)
368             show_stream(fmt_ctx, i);
369
370     if (do_show_format)
371         show_format(fmt_ctx);
372
373     avformat_close_input(&fmt_ctx);
374     return 0;
375 }
376
377 static void show_usage(void)
378 {
379     printf("Simple multimedia streams analyzer\n");
380     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
381     printf("\n");
382 }
383
384 static int opt_format(const char *opt, const char *arg)
385 {
386     iformat = av_find_input_format(arg);
387     if (!iformat) {
388         fprintf(stderr, "Unknown input format: %s\n", arg);
389         return AVERROR(EINVAL);
390     }
391     return 0;
392 }
393
394 static int opt_show_format_entry(const char *opt, const char *arg)
395 {
396     do_show_format = 1;
397     av_dict_set(&fmt_entries_to_show, arg, "", 0);
398     return 0;
399 }
400
401 static void opt_input_file(void *optctx, const char *arg)
402 {
403     if (input_filename) {
404         fprintf(stderr,
405                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
406                 arg, input_filename);
407         exit(1);
408     }
409     if (!strcmp(arg, "-"))
410         arg = "pipe:";
411     input_filename = arg;
412 }
413
414 static void show_help(void)
415 {
416     av_log_set_callback(log_callback_help);
417     show_usage();
418     show_help_options(options, "Main options:\n", 0, 0);
419     printf("\n");
420     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
421 }
422
423 static void opt_pretty(void)
424 {
425     show_value_unit              = 1;
426     use_value_prefix             = 1;
427     use_byte_value_binary_prefix = 1;
428     use_value_sexagesimal_format = 1;
429 }
430
431 static const OptionDef options[] = {
432 #include "cmdutils_common_opts.h"
433     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
434     { "unit", OPT_BOOL, {(void*)&show_value_unit},
435       "show unit of the displayed values" },
436     { "prefix", OPT_BOOL, {(void*)&use_value_prefix},
437       "use SI prefixes for the displayed values" },
438     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
439       "use binary prefixes for byte units" },
440     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
441       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
442     { "pretty", 0, {(void*)&opt_pretty},
443       "prettify the format of displayed values, make it more human readable" },
444     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
445     { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
446       "show a particular entry from the format/container info", "entry" },
447     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
448     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
449     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default},
450       "generic catch all option", "" },
451     { NULL, },
452 };
453
454 int main(int argc, char **argv)
455 {
456     int ret;
457
458     parse_loglevel(argc, argv, options);
459     av_register_all();
460     avformat_network_init();
461     init_opts();
462 #if CONFIG_AVDEVICE
463     avdevice_register_all();
464 #endif
465
466     show_banner();
467     parse_options(NULL, argc, argv, options, opt_input_file);
468
469     if (!input_filename) {
470         show_usage();
471         fprintf(stderr, "You have to specify one input file.\n");
472         fprintf(stderr,
473                 "Use -h to get full help or, even better, run 'man %s'.\n",
474                 program_name);
475         exit(1);
476     }
477
478     ret = probe_file(input_filename);
479
480     avformat_network_deinit();
481
482     return ret;
483 }