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