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