avprobe: restore pseudo-INI old style format for compatibility.
[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 /*
68  * The output is structured in array and objects that might contain items
69  * Array could require the objects within to not be named.
70  * Object could require the items within to be named.
71  *
72  * For flat representation the name of each section is saved on prefix so it
73  * can be rendered in order to represent nested structures (e.g. array of
74  * objects for the packets list).
75  *
76  * Within an array each element can need an unique identifier or an index.
77  *
78  * Nesting level is accounted separately.
79  */
80
81 typedef enum {
82     ARRAY,
83     OBJECT
84 } ProbeElementType;
85
86 typedef struct {
87     const char *name;
88     ProbeElementType type;
89     int64_t index;
90     int64_t nb_elems;
91 } ProbeElement;
92
93 typedef struct {
94     ProbeElement *prefix;
95     int level;
96 } OutputContext;
97
98 static AVIOContext *probe_out = NULL;
99 static OutputContext octx;
100 #define AVP_INDENT() avio_printf(probe_out, "%*c", octx.level * 2, ' ')
101
102 /*
103  * Default format, INI
104  *
105  * - all key and values are utf8
106  * - '.' is the subgroup separator
107  * - newlines and the following characters are escaped
108  * - '\' is the escape character
109  * - '#' is the comment
110  * - '=' is the key/value separators
111  * - ':' is not used but usually parsed as key/value separator
112  */
113
114 static void ini_print_header(void)
115 {
116     avio_printf(probe_out, "# avprobe output\n\n");
117 }
118 static void ini_print_footer(void)
119 {
120     avio_w8(probe_out, '\n');
121 }
122
123 static void ini_escape_print(const char *s)
124 {
125     int i = 0;
126     char c = 0;
127
128     while (c = s[i++]) {
129         switch (c) {
130         case '\r': avio_printf(probe_out, "%s", "\\r"); break;
131         case '\n': avio_printf(probe_out, "%s", "\\n"); break;
132         case '\f': avio_printf(probe_out, "%s", "\\f"); break;
133         case '\b': avio_printf(probe_out, "%s", "\\b"); break;
134         case '\t': avio_printf(probe_out, "%s", "\\t"); break;
135         case '\\':
136         case '#' :
137         case '=' :
138         case ':' : avio_w8(probe_out, '\\');
139         default:
140             if ((unsigned char)c < 32)
141                 avio_printf(probe_out, "\\x00%02x", c & 0xff);
142             else
143                 avio_w8(probe_out, c);
144         break;
145         }
146     }
147 }
148
149 static void ini_print_array_header(const char *name)
150 {
151     if (octx.prefix[octx.level -1].nb_elems)
152         avio_printf(probe_out, "\n");
153 }
154
155 static void ini_print_object_header(const char *name)
156 {
157     int i;
158     ProbeElement *el = octx.prefix + octx.level -1;
159
160     if (el->nb_elems)
161         avio_printf(probe_out, "\n");
162
163     avio_printf(probe_out, "[");
164
165     for (i = 1; i < octx.level; i++) {
166         el = octx.prefix + i;
167         avio_printf(probe_out, "%s.", el->name);
168         if (el->index >= 0)
169             avio_printf(probe_out, "%"PRId64".", el->index);
170     }
171
172     avio_printf(probe_out, "%s", name);
173     if (el && el->type == ARRAY)
174         avio_printf(probe_out, ".%"PRId64"", el->nb_elems);
175     avio_printf(probe_out, "]\n");
176 }
177
178 static void ini_print_integer(const char *key, int64_t value)
179 {
180     ini_escape_print(key);
181     avio_printf(probe_out, "=%"PRId64"\n", value);
182 }
183
184
185 static void ini_print_string(const char *key, const char *value)
186 {
187     ini_escape_print(key);
188     avio_printf(probe_out, "=");
189     ini_escape_print(value);
190     avio_w8(probe_out, '\n');
191 }
192
193 /*
194  * Alternate format, JSON
195  */
196
197 static void json_print_header(void)
198 {
199     avio_printf(probe_out, "{");
200 }
201 static void json_print_footer(void)
202 {
203     avio_printf(probe_out, "}\n");
204 }
205
206 static void json_print_array_header(const char *name)
207 {
208     if (octx.prefix[octx.level -1].nb_elems)
209         avio_printf(probe_out, ",\n");
210     AVP_INDENT();
211     avio_printf(probe_out, "\"%s\" : ", name);
212     avio_printf(probe_out, "[\n");
213 }
214
215 static void json_print_array_footer(const char *name)
216 {
217     avio_printf(probe_out, "\n");
218     AVP_INDENT();
219     avio_printf(probe_out, "]");
220 }
221
222 static void json_print_object_header(const char *name)
223 {
224     if (octx.prefix[octx.level -1].nb_elems)
225         avio_printf(probe_out, ",\n");
226     AVP_INDENT();
227     if (octx.prefix[octx.level -1].type == OBJECT)
228         avio_printf(probe_out, "\"%s\" : ", name);
229     avio_printf(probe_out, "{\n");
230 }
231
232 static void json_print_object_footer(const char *name)
233 {
234     avio_printf(probe_out, "\n");
235     AVP_INDENT();
236     avio_printf(probe_out, "}");
237 }
238
239 static void json_print_integer(const char *key, int64_t value)
240 {
241     if (octx.prefix[octx.level -1].nb_elems)
242         avio_printf(probe_out, ",\n");
243     AVP_INDENT();
244     avio_printf(probe_out, "\"%s\" : %"PRId64"", key, value);
245 }
246
247 static void json_escape_print(const char *s)
248 {
249     int i = 0;
250     char c = 0;
251
252     while (c = s[i++]) {
253         switch (c) {
254         case '\r': avio_printf(probe_out, "%s", "\\r"); break;
255         case '\n': avio_printf(probe_out, "%s", "\\n"); break;
256         case '\f': avio_printf(probe_out, "%s", "\\f"); break;
257         case '\b': avio_printf(probe_out, "%s", "\\b"); break;
258         case '\t': avio_printf(probe_out, "%s", "\\t"); break;
259         case '\\':
260         case '"' : avio_w8(probe_out, '\\');
261         default:
262             if ((unsigned char)c < 32)
263                 avio_printf(probe_out, "\\u00%02x", c & 0xff);
264             else
265                 avio_w8(probe_out, c);
266         break;
267         }
268     }
269 }
270
271 static void json_print_string(const char *key, const char *value)
272 {
273     if (octx.prefix[octx.level -1].nb_elems)
274         avio_printf(probe_out, ",\n");
275     AVP_INDENT();
276     avio_w8(probe_out, '\"');
277     json_escape_print(key);
278     avio_printf(probe_out, "\" : \"");
279     json_escape_print(value);
280     avio_w8(probe_out, '\"');
281 }
282
283 /*
284  * old-style pseudo-INI
285  */
286 static void old_print_object_header(const char *name)
287 {
288     char *str, *p;
289
290     if (!strcmp(name, "tags"))
291         return;
292
293     str = p = av_strdup(name);
294     while (*p) {
295         *p = toupper(*p);
296         p++;
297     }
298
299     avio_printf(probe_out, "[%s]\n", str);
300     av_freep(&str);
301 }
302
303 static void old_print_object_footer(const char *name)
304 {
305     char *str, *p;
306
307     if (!strcmp(name, "tags"))
308         return;
309
310     str = p = av_strdup(name);
311     while (*p) {
312         *p = toupper(*p);
313         p++;
314     }
315
316     avio_printf(probe_out, "[/%s]\n", str);
317     av_freep(&str);
318 }
319
320 static void old_print_string(const char *key, const char *value)
321 {
322     if (!strcmp(octx.prefix[octx.level - 1].name, "tags"))
323         avio_printf(probe_out, "TAG:");
324     ini_print_string(key, value);
325 }
326
327 /*
328  * Simple Formatter for single entries.
329  */
330
331 static void show_format_entry_integer(const char *key, int64_t value)
332 {
333     if (key && av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
334         if (nb_fmt_entries_to_show > 1)
335             avio_printf(probe_out, "%s=", key);
336         avio_printf(probe_out, "%"PRId64"\n", value);
337     }
338 }
339
340 static void show_format_entry_string(const char *key, const char *value)
341 {
342     if (key && av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
343         if (nb_fmt_entries_to_show > 1)
344             avio_printf(probe_out, "%s=", key);
345         avio_printf(probe_out, "%s\n", value);
346     }
347 }
348
349
350 void (*print_header)(void) = ini_print_header;
351 void (*print_footer)(void) = ini_print_footer;
352
353 void (*print_array_header) (const char *name) = ini_print_array_header;
354 void (*print_array_footer) (const char *name);
355 void (*print_object_header)(const char *name) = ini_print_object_header;
356 void (*print_object_footer)(const char *name);
357
358 void (*print_integer) (const char *key, int64_t value)     = ini_print_integer;
359 void (*print_string)  (const char *key, const char *value) = ini_print_string;
360
361
362 static void probe_group_enter(const char *name, int type)
363 {
364     int64_t count = -1;
365
366     octx.prefix =
367         av_realloc(octx.prefix, sizeof(ProbeElement) * (octx.level + 1));
368
369     if (!octx.prefix || !name) {
370         fprintf(stderr, "Out of memory\n");
371         exit(1);
372     }
373
374     if (octx.level) {
375         ProbeElement *parent = octx.prefix + octx.level -1;
376         if (parent->type == ARRAY)
377             count = parent->nb_elems;
378         parent->nb_elems++;
379     }
380
381     octx.prefix[octx.level++] = (ProbeElement){name, type, count, 0};
382 }
383
384 static void probe_group_leave(void)
385 {
386     --octx.level;
387 }
388
389 static void probe_header(void)
390 {
391     if (print_header)
392         print_header();
393     probe_group_enter("root", OBJECT);
394 }
395
396 static void probe_footer(void)
397 {
398     if (print_footer)
399         print_footer();
400     probe_group_leave();
401 }
402
403
404 static void probe_array_header(const char *name)
405 {
406     if (print_array_header)
407         print_array_header(name);
408
409     probe_group_enter(name, ARRAY);
410 }
411
412 static void probe_array_footer(const char *name)
413 {
414     probe_group_leave();
415     if (print_array_footer)
416         print_array_footer(name);
417 }
418
419 static void probe_object_header(const char *name)
420 {
421     if (print_object_header)
422         print_object_header(name);
423
424     probe_group_enter(name, OBJECT);
425 }
426
427 static void probe_object_footer(const char *name)
428 {
429     probe_group_leave();
430     if (print_object_footer)
431         print_object_footer(name);
432 }
433
434 static void probe_int(const char *key, int64_t value)
435 {
436     print_integer(key, value);
437     octx.prefix[octx.level -1].nb_elems++;
438 }
439
440 static void probe_str(const char *key, const char *value)
441 {
442     print_string(key, value);
443     octx.prefix[octx.level -1].nb_elems++;
444 }
445
446 static void probe_dict(AVDictionary *dict, const char *name)
447 {
448     AVDictionaryEntry *entry = NULL;
449     if (!dict)
450         return;
451     probe_object_header(name);
452     while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) {
453         probe_str(entry->key, entry->value);
454     }
455     probe_object_footer(name);
456 }
457
458 static char *value_string(char *buf, int buf_size, double val, const char *unit)
459 {
460     if (unit == unit_second_str && use_value_sexagesimal_format) {
461         double secs;
462         int hours, mins;
463         secs  = val;
464         mins  = (int)secs / 60;
465         secs  = secs - mins * 60;
466         hours = mins / 60;
467         mins %= 60;
468         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
469     } else if (use_value_prefix) {
470         const char *prefix_string;
471         int index;
472
473         if (unit == unit_byte_str && use_byte_value_binary_prefix) {
474             index = (int) (log(val)/log(2)) / 10;
475             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
476             val  /= pow(2, index * 10);
477             prefix_string = binary_unit_prefixes[index];
478         } else {
479             index = (int) (log10(val)) / 3;
480             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
481             val  /= pow(10, index * 3);
482             prefix_string = decimal_unit_prefixes[index];
483         }
484         snprintf(buf, buf_size, "%.*f%s%s",
485                  index ? 3 : 0, val,
486                  prefix_string,
487                  show_value_unit ? unit : "");
488     } else {
489         snprintf(buf, buf_size, "%f%s", val, show_value_unit ? unit : "");
490     }
491
492     return buf;
493 }
494
495 static char *time_value_string(char *buf, int buf_size, int64_t val,
496                                const AVRational *time_base)
497 {
498     if (val == AV_NOPTS_VALUE) {
499         snprintf(buf, buf_size, "N/A");
500     } else {
501         value_string(buf, buf_size, val * av_q2d(*time_base), unit_second_str);
502     }
503
504     return buf;
505 }
506
507 static char *ts_value_string(char *buf, int buf_size, int64_t ts)
508 {
509     if (ts == AV_NOPTS_VALUE) {
510         snprintf(buf, buf_size, "N/A");
511     } else {
512         snprintf(buf, buf_size, "%"PRId64, ts);
513     }
514
515     return buf;
516 }
517
518 static char *rational_string(char *buf, int buf_size, const char *sep,
519                              const AVRational *rat)
520 {
521     snprintf(buf, buf_size, "%d%s%d", rat->num, sep, rat->den);
522     return buf;
523 }
524
525 static char *tag_string(char *buf, int buf_size, int tag)
526 {
527     snprintf(buf, buf_size, "0x%04x", tag);
528     return buf;
529 }
530
531
532
533 static const char *media_type_string(enum AVMediaType media_type)
534 {
535     switch (media_type) {
536     case AVMEDIA_TYPE_VIDEO:      return "video";
537     case AVMEDIA_TYPE_AUDIO:      return "audio";
538     case AVMEDIA_TYPE_DATA:       return "data";
539     case AVMEDIA_TYPE_SUBTITLE:   return "subtitle";
540     case AVMEDIA_TYPE_ATTACHMENT: return "attachment";
541     default:                      return "unknown";
542     }
543 }
544
545 static void show_packet(AVFormatContext *fmt_ctx, AVPacket *pkt)
546 {
547     char val_str[128];
548     AVStream *st = fmt_ctx->streams[pkt->stream_index];
549
550     probe_object_header("packet");
551     probe_str("codec_type", media_type_string(st->codec->codec_type));
552     probe_int("stream_index", pkt->stream_index);
553     probe_str("pts", ts_value_string(val_str, sizeof(val_str), pkt->pts));
554     probe_str("pts_time", time_value_string(val_str, sizeof(val_str),
555                                                pkt->pts, &st->time_base));
556     probe_str("dts", ts_value_string(val_str, sizeof(val_str), pkt->dts));
557     probe_str("dts_time", time_value_string(val_str, sizeof(val_str),
558                                                pkt->dts, &st->time_base));
559     probe_str("duration", ts_value_string(val_str, sizeof(val_str),
560                                              pkt->duration));
561     probe_str("duration_time", time_value_string(val_str, sizeof(val_str),
562                                                     pkt->duration,
563                                                     &st->time_base));
564     probe_str("size", value_string(val_str, sizeof(val_str),
565                                       pkt->size, unit_byte_str));
566     probe_int("pos", pkt->pos);
567     probe_str("flags", pkt->flags & AV_PKT_FLAG_KEY ? "K" : "_");
568     probe_object_footer("packet");
569 }
570
571 static void show_packets(AVFormatContext *fmt_ctx)
572 {
573     AVPacket pkt;
574
575     av_init_packet(&pkt);
576     probe_array_header("packets");
577     while (!av_read_frame(fmt_ctx, &pkt))
578         show_packet(fmt_ctx, &pkt);
579     probe_array_footer("packets");
580 }
581
582 static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)
583 {
584     AVStream *stream = fmt_ctx->streams[stream_idx];
585     AVCodecContext *dec_ctx;
586     AVCodec *dec;
587     const char *profile;
588     char val_str[128];
589     AVRational display_aspect_ratio;
590
591     probe_object_header("stream");
592
593     probe_int("index", stream->index);
594
595     if ((dec_ctx = stream->codec)) {
596         if ((dec = dec_ctx->codec)) {
597             probe_str("codec_name", dec->name);
598             probe_str("codec_long_name", dec->long_name);
599         } else {
600             probe_str("codec_name", "unknown");
601         }
602
603         probe_str("codec_type", media_type_string(dec_ctx->codec_type));
604         probe_str("codec_time_base",
605                   rational_string(val_str, sizeof(val_str),
606                                   "/", &dec_ctx->time_base));
607
608         /* print AVI/FourCC tag */
609         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
610         probe_str("codec_tag_string", val_str);
611         probe_str("codec_tag", tag_string(val_str, sizeof(val_str),
612                                           dec_ctx->codec_tag));
613
614         /* print profile, if there is one */
615         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
616             probe_str("profile", profile);
617
618         switch (dec_ctx->codec_type) {
619         case AVMEDIA_TYPE_VIDEO:
620             probe_int("width", dec_ctx->width);
621             probe_int("height", dec_ctx->height);
622             probe_int("has_b_frames", dec_ctx->has_b_frames);
623             if (dec_ctx->sample_aspect_ratio.num) {
624                 probe_str("sample_aspect_ratio",
625                           rational_string(val_str, sizeof(val_str), ":",
626                           &dec_ctx->sample_aspect_ratio));
627                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
628                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
629                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
630                           1024*1024);
631                 probe_str("display_aspect_ratio",
632                           rational_string(val_str, sizeof(val_str), ":",
633                           &display_aspect_ratio));
634             }
635             probe_str("pix_fmt",
636                       dec_ctx->pix_fmt != PIX_FMT_NONE ? av_pix_fmt_descriptors[dec_ctx->pix_fmt].name
637                                                     : "unknown");
638             probe_int("level", dec_ctx->level);
639             break;
640
641         case AVMEDIA_TYPE_AUDIO:
642             probe_str("sample_rate",
643                       value_string(val_str, sizeof(val_str),
644                                    dec_ctx->sample_rate,
645                                    unit_hertz_str));
646             probe_int("channels", dec_ctx->channels);
647             probe_int("bits_per_sample",
648                       av_get_bits_per_sample(dec_ctx->codec_id));
649             break;
650         }
651     } else {
652         probe_str("codec_type", "unknown");
653     }
654
655     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
656         probe_int("id", stream->id);
657     probe_str("r_frame_rate",
658               rational_string(val_str, sizeof(val_str), "/",
659               &stream->r_frame_rate));
660     probe_str("avg_frame_rate",
661               rational_string(val_str, sizeof(val_str), "/",
662               &stream->avg_frame_rate));
663     probe_str("time_base",
664               rational_string(val_str, sizeof(val_str), "/",
665               &stream->time_base));
666     probe_str("start_time",
667               time_value_string(val_str, sizeof(val_str),
668                                 stream->start_time, &stream->time_base));
669     probe_str("duration",
670               time_value_string(val_str, sizeof(val_str),
671                                 stream->duration, &stream->time_base));
672     if (stream->nb_frames)
673         probe_int("nb_frames", stream->nb_frames);
674
675     probe_dict(stream->metadata, "tags");
676
677     probe_object_footer("stream");
678 }
679
680 static void show_format(AVFormatContext *fmt_ctx)
681 {
682     char val_str[128];
683     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
684
685     probe_object_header("format");
686     probe_str("filename",         fmt_ctx->filename);
687     probe_int("nb_streams",       fmt_ctx->nb_streams);
688     probe_str("format_name",      fmt_ctx->iformat->name);
689     probe_str("format_long_name", fmt_ctx->iformat->long_name);
690     probe_str("start_time",
691                        time_value_string(val_str, sizeof(val_str),
692                                          fmt_ctx->start_time, &AV_TIME_BASE_Q));
693     probe_str("duration",
694                        time_value_string(val_str, sizeof(val_str),
695                                          fmt_ctx->duration, &AV_TIME_BASE_Q));
696     probe_str("size",
697                        size >= 0 ? value_string(val_str, sizeof(val_str),
698                                                 size, unit_byte_str)
699                                   : "unknown");
700     probe_str("bit_rate",
701                        value_string(val_str, sizeof(val_str),
702                                     fmt_ctx->bit_rate, unit_bit_per_second_str));
703
704     probe_dict(fmt_ctx->metadata, "tags");
705
706     probe_object_footer("format");
707 }
708
709 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
710 {
711     int err, i;
712     AVFormatContext *fmt_ctx = NULL;
713     AVDictionaryEntry *t;
714
715     if ((err = avformat_open_input(&fmt_ctx, filename,
716                                    iformat, &format_opts)) < 0) {
717         print_error(filename, err);
718         return err;
719     }
720     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
721         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
722         return AVERROR_OPTION_NOT_FOUND;
723     }
724
725
726     /* fill the streams in the format context */
727     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
728         print_error(filename, err);
729         return err;
730     }
731
732     av_dump_format(fmt_ctx, 0, filename, 0);
733
734     /* bind a decoder to each input stream */
735     for (i = 0; i < fmt_ctx->nb_streams; i++) {
736         AVStream *stream = fmt_ctx->streams[i];
737         AVCodec *codec;
738
739         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
740             fprintf(stderr,
741                     "Unsupported codec with id %d for input stream %d\n",
742                     stream->codec->codec_id, stream->index);
743         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
744             fprintf(stderr, "Error while opening codec for input stream %d\n",
745                     stream->index);
746         }
747     }
748
749     *fmt_ctx_ptr = fmt_ctx;
750     return 0;
751 }
752
753 static void close_input_file(AVFormatContext **ctx_ptr)
754 {
755     int i;
756     AVFormatContext *fmt_ctx = *ctx_ptr;
757
758     /* close decoder for each stream */
759     for (i = 0; i < fmt_ctx->nb_streams; i++) {
760         AVStream *stream = fmt_ctx->streams[i];
761
762         avcodec_close(stream->codec);
763     }
764     avformat_close_input(ctx_ptr);
765 }
766
767 static int probe_file(const char *filename)
768 {
769     AVFormatContext *fmt_ctx;
770     int ret, i;
771
772     if ((ret = open_input_file(&fmt_ctx, filename)))
773         return ret;
774
775     if (do_show_format)
776         show_format(fmt_ctx);
777
778     if (do_show_streams) {
779         probe_array_header("streams");
780         for (i = 0; i < fmt_ctx->nb_streams; i++)
781             show_stream(fmt_ctx, i);
782         probe_array_footer("streams");
783     }
784
785     if (do_show_packets)
786         show_packets(fmt_ctx);
787
788     close_input_file(&fmt_ctx);
789     return 0;
790 }
791
792 static void show_usage(void)
793 {
794     printf("Simple multimedia streams analyzer\n");
795     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
796     printf("\n");
797 }
798
799 static int opt_format(const char *opt, const char *arg)
800 {
801     iformat = av_find_input_format(arg);
802     if (!iformat) {
803         fprintf(stderr, "Unknown input format: %s\n", arg);
804         return AVERROR(EINVAL);
805     }
806     return 0;
807 }
808
809 static int opt_output_format(const char *opt, const char *arg)
810 {
811
812     if (!strcmp(arg, "json")) {
813         print_header        = json_print_header;
814         print_footer        = json_print_footer;
815         print_array_header  = json_print_array_header;
816         print_array_footer  = json_print_array_footer;
817         print_object_header = json_print_object_header;
818         print_object_footer = json_print_object_footer;
819
820         print_integer = json_print_integer;
821         print_string  = json_print_string;
822     } else if (!strcmp(arg, "ini")) {
823         print_header        = ini_print_header;
824         print_footer        = ini_print_footer;
825         print_array_header  = ini_print_array_header;
826         print_object_header = ini_print_object_header;
827
828         print_integer = ini_print_integer;
829         print_string  = ini_print_string;
830     } else if (!strcmp(arg, "old")) {
831         print_header        = NULL;
832         print_object_header = old_print_object_header;
833         print_object_footer = old_print_object_footer;
834
835         print_string        = old_print_string;
836     } else {
837         av_log(NULL, AV_LOG_ERROR, "Unsupported formatter %s\n", arg);
838         return AVERROR(EINVAL);
839     }
840     return 0;
841 }
842
843 static int opt_show_format_entry(const char *opt, const char *arg)
844 {
845     do_show_format = 1;
846     nb_fmt_entries_to_show++;
847     print_header        = NULL;
848     print_footer        = NULL;
849     print_array_header  = NULL;
850     print_array_footer  = NULL;
851     print_object_header = NULL;
852     print_object_footer = NULL;
853
854     print_integer = show_format_entry_integer;
855     print_string  = show_format_entry_string;
856     av_dict_set(&fmt_entries_to_show, arg, "", 0);
857     return 0;
858 }
859
860 static void opt_input_file(void *optctx, const char *arg)
861 {
862     if (input_filename) {
863         fprintf(stderr,
864                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
865                 arg, input_filename);
866         exit(1);
867     }
868     if (!strcmp(arg, "-"))
869         arg = "pipe:";
870     input_filename = arg;
871 }
872
873 static void show_help(void)
874 {
875     av_log_set_callback(log_callback_help);
876     show_usage();
877     show_help_options(options, "Main options:\n", 0, 0);
878     printf("\n");
879     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
880 }
881
882 static void opt_pretty(void)
883 {
884     show_value_unit              = 1;
885     use_value_prefix             = 1;
886     use_byte_value_binary_prefix = 1;
887     use_value_sexagesimal_format = 1;
888 }
889
890 static const OptionDef options[] = {
891 #include "cmdutils_common_opts.h"
892     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
893     { "of", HAS_ARG, {(void*)&opt_output_format}, "output the document either as ini or json", "output_format" },
894     { "unit", OPT_BOOL, {(void*)&show_value_unit},
895       "show unit of the displayed values" },
896     { "prefix", OPT_BOOL, {(void*)&use_value_prefix},
897       "use SI prefixes for the displayed values" },
898     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
899       "use binary prefixes for byte units" },
900     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
901       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
902     { "pretty", 0, {(void*)&opt_pretty},
903       "prettify the format of displayed values, make it more human readable" },
904     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
905     { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
906       "show a particular entry from the format/container info", "entry" },
907     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
908     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
909     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default},
910       "generic catch all option", "" },
911     { NULL, },
912 };
913
914 static int probe_buf_write(void *opaque, uint8_t *buf, int buf_size)
915 {
916     printf("%.*s", buf_size, buf);
917     return 0;
918 }
919
920 #define AVP_BUFFSIZE 4096
921
922 int main(int argc, char **argv)
923 {
924     int ret;
925     uint8_t *buffer = av_malloc(AVP_BUFFSIZE);
926
927     if (!buffer)
928         exit(1);
929
930     parse_loglevel(argc, argv, options);
931     av_register_all();
932     avformat_network_init();
933     init_opts();
934 #if CONFIG_AVDEVICE
935     avdevice_register_all();
936 #endif
937
938     show_banner();
939     parse_options(NULL, argc, argv, options, opt_input_file);
940
941     if (!input_filename) {
942         show_usage();
943         fprintf(stderr, "You have to specify one input file.\n");
944         fprintf(stderr,
945                 "Use -h to get full help or, even better, run 'man %s'.\n",
946                 program_name);
947         exit(1);
948     }
949
950     probe_out = avio_alloc_context(buffer, AVP_BUFFSIZE, 1, NULL, NULL,
951                                  probe_buf_write, NULL);
952     if (!probe_out)
953         exit(1);
954
955     probe_header();
956     ret = probe_file(input_filename);
957     probe_footer();
958     avio_flush(probe_out);
959     avio_close(probe_out);
960
961     avformat_network_deinit();
962
963     return ret;
964 }