]> git.sesse.net Git - ffmpeg/blob - avprobe.c
dvbsub: cosmetics: Group all debug code together
[ffmpeg] / 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/avstring.h"
27 #include "libavutil/display.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/stereo3d.h"
31 #include "libavutil/dict.h"
32 #include "libavutil/libm.h"
33 #include "libavdevice/avdevice.h"
34 #include "cmdutils.h"
35
36 typedef struct InputStream {
37     AVStream *st;
38
39     AVCodecContext *dec_ctx;
40 } InputStream;
41
42 typedef struct InputFile {
43     AVFormatContext *fmt_ctx;
44
45     InputStream *streams;
46     int       nb_streams;
47 } InputFile;
48
49 const char program_name[] = "avprobe";
50 const int program_birth_year = 2007;
51
52 static int do_show_format  = 0;
53 static AVDictionary *fmt_entries_to_show = NULL;
54 static int nb_fmt_entries_to_show;
55 static int do_show_packets = 0;
56 static int do_show_streams = 0;
57 static AVDictionary *stream_entries_to_show = NULL;
58 static int nb_stream_entries_to_show;
59
60 /* key used to print when probe_{int,str}(NULL, ..) is invoked */
61 static const char *header_key;
62
63 static int show_value_unit              = 0;
64 static int use_value_prefix             = 0;
65 static int use_byte_value_binary_prefix = 0;
66 static int use_value_sexagesimal_format = 0;
67
68 /* globals */
69 static const OptionDef *options;
70
71 /* avprobe context */
72 static const char *input_filename;
73 static AVInputFormat *iformat = NULL;
74
75 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
76 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
77
78 static const char unit_second_str[]         = "s"    ;
79 static const char unit_hertz_str[]          = "Hz"   ;
80 static const char unit_byte_str[]           = "byte" ;
81 static const char unit_bit_per_second_str[] = "bit/s";
82
83 static void avprobe_cleanup(int ret)
84 {
85     av_dict_free(&fmt_entries_to_show);
86     av_dict_free(&stream_entries_to_show);
87 }
88
89 /*
90  * The output is structured in array and objects that might contain items
91  * Array could require the objects within to not be named.
92  * Object could require the items within to be named.
93  *
94  * For flat representation the name of each section is saved on prefix so it
95  * can be rendered in order to represent nested structures (e.g. array of
96  * objects for the packets list).
97  *
98  * Within an array each element can need an unique identifier or an index.
99  *
100  * Nesting level is accounted separately.
101  */
102
103 typedef enum {
104     ARRAY,
105     OBJECT
106 } PrintElementType;
107
108 typedef struct PrintElement {
109     const char *name;
110     PrintElementType type;
111     int64_t index;
112     int64_t nb_elems;
113 } PrintElement;
114
115 typedef struct PrintContext {
116     PrintElement *prefix;
117     int level;
118     void (*print_header)(void);
119     void (*print_footer)(void);
120
121     void (*print_array_header) (const char *name, int plain_values);
122     void (*print_array_footer) (const char *name, int plain_values);
123     void (*print_object_header)(const char *name);
124     void (*print_object_footer)(const char *name);
125
126     void (*print_integer) (const char *key, int64_t value);
127     void (*print_string)  (const char *key, const char *value);
128 } PrintContext;
129
130 static AVIOContext *probe_out = NULL;
131 static PrintContext octx;
132 #define AVP_INDENT() avio_printf(probe_out, "%*c", octx.level * 2, ' ')
133
134 /*
135  * Default format, INI
136  *
137  * - all key and values are utf8
138  * - '.' is the subgroup separator
139  * - newlines and the following characters are escaped
140  * - '\' is the escape character
141  * - '#' is the comment
142  * - '=' is the key/value separators
143  * - ':' is not used but usually parsed as key/value separator
144  */
145
146 static void ini_print_header(void)
147 {
148     avio_printf(probe_out, "# avprobe output\n\n");
149 }
150 static void ini_print_footer(void)
151 {
152     avio_w8(probe_out, '\n');
153 }
154
155 static void ini_escape_print(const char *s)
156 {
157     int i = 0;
158     char c = 0;
159
160     while (c = s[i++]) {
161         switch (c) {
162         case '\r': avio_printf(probe_out, "%s", "\\r"); break;
163         case '\n': avio_printf(probe_out, "%s", "\\n"); break;
164         case '\f': avio_printf(probe_out, "%s", "\\f"); break;
165         case '\b': avio_printf(probe_out, "%s", "\\b"); break;
166         case '\t': avio_printf(probe_out, "%s", "\\t"); break;
167         case '\\':
168         case '#' :
169         case '=' :
170         case ':' : avio_w8(probe_out, '\\');
171         default:
172             if ((unsigned char)c < 32)
173                 avio_printf(probe_out, "\\x00%02x", c & 0xff);
174             else
175                 avio_w8(probe_out, c);
176         break;
177         }
178     }
179 }
180
181 static void ini_print_array_header(const char *name, int plain_values)
182 {
183     if (!plain_values) {
184         /* Add a new line if we create a new full group */
185         if (octx.prefix[octx.level -1].nb_elems)
186             avio_printf(probe_out, "\n");
187     } else {
188         ini_escape_print(name);
189         avio_w8(probe_out, '=');
190     }
191 }
192
193 static void ini_print_array_footer(const char *name, int plain_values)
194 {
195     if (plain_values)
196         avio_printf(probe_out, "\n");
197 }
198
199 static void ini_print_object_header(const char *name)
200 {
201     int i;
202     PrintElement *el = octx.prefix + octx.level -1;
203
204     if (el->nb_elems)
205         avio_printf(probe_out, "\n");
206
207     avio_printf(probe_out, "[");
208
209     for (i = 1; i < octx.level; i++) {
210         el = octx.prefix + i;
211         avio_printf(probe_out, "%s.", el->name);
212         if (el->index >= 0)
213             avio_printf(probe_out, "%"PRId64".", el->index);
214     }
215
216     avio_printf(probe_out, "%s", name);
217     if (el->type == ARRAY)
218         avio_printf(probe_out, ".%"PRId64"", el->nb_elems);
219     avio_printf(probe_out, "]\n");
220 }
221
222 static void ini_print_integer(const char *key, int64_t value)
223 {
224     if (key) {
225         ini_escape_print(key);
226         avio_printf(probe_out, "=%"PRId64"\n", value);
227     } else {
228         if (octx.prefix[octx.level -1].nb_elems)
229             avio_printf(probe_out, ",");
230         avio_printf(probe_out, "%"PRId64, value);
231     }
232 }
233
234
235 static void ini_print_string(const char *key, const char *value)
236 {
237     ini_escape_print(key);
238     avio_printf(probe_out, "=");
239     ini_escape_print(value);
240     avio_w8(probe_out, '\n');
241 }
242
243 /*
244  * Alternate format, JSON
245  */
246
247 static void json_print_header(void)
248 {
249     avio_printf(probe_out, "{");
250 }
251 static void json_print_footer(void)
252 {
253     avio_printf(probe_out, "}\n");
254 }
255
256 static void json_print_array_header(const char *name, int plain_values)
257 {
258     if (octx.prefix[octx.level -1].nb_elems)
259         avio_printf(probe_out, ",\n");
260     AVP_INDENT();
261     avio_printf(probe_out, "\"%s\" : ", name);
262     avio_printf(probe_out, "[\n");
263 }
264
265 static void json_print_array_footer(const char *name, int plain_values)
266 {
267     avio_printf(probe_out, "\n");
268     AVP_INDENT();
269     avio_printf(probe_out, "]");
270 }
271
272 static void json_print_object_header(const char *name)
273 {
274     if (octx.prefix[octx.level -1].nb_elems)
275         avio_printf(probe_out, ",\n");
276     AVP_INDENT();
277     if (octx.prefix[octx.level -1].type == OBJECT)
278         avio_printf(probe_out, "\"%s\" : ", name);
279     avio_printf(probe_out, "{\n");
280 }
281
282 static void json_print_object_footer(const char *name)
283 {
284     avio_printf(probe_out, "\n");
285     AVP_INDENT();
286     avio_printf(probe_out, "}");
287 }
288
289 static void json_print_integer(const char *key, int64_t value)
290 {
291     if (key) {
292         if (octx.prefix[octx.level -1].nb_elems)
293             avio_printf(probe_out, ",\n");
294         AVP_INDENT();
295         avio_printf(probe_out, "\"%s\" : ", key);
296     } else {
297         if (octx.prefix[octx.level -1].nb_elems)
298             avio_printf(probe_out, ", ");
299         else
300             AVP_INDENT();
301     }
302     avio_printf(probe_out, "%"PRId64, value);
303 }
304
305 static void json_escape_print(const char *s)
306 {
307     int i = 0;
308     char c = 0;
309
310     while (c = s[i++]) {
311         switch (c) {
312         case '\r': avio_printf(probe_out, "%s", "\\r"); break;
313         case '\n': avio_printf(probe_out, "%s", "\\n"); break;
314         case '\f': avio_printf(probe_out, "%s", "\\f"); break;
315         case '\b': avio_printf(probe_out, "%s", "\\b"); break;
316         case '\t': avio_printf(probe_out, "%s", "\\t"); break;
317         case '\\':
318         case '"' : avio_w8(probe_out, '\\');
319         default:
320             if ((unsigned char)c < 32)
321                 avio_printf(probe_out, "\\u00%02x", c & 0xff);
322             else
323                 avio_w8(probe_out, c);
324         break;
325         }
326     }
327 }
328
329 static void json_print_string(const char *key, const char *value)
330 {
331     if (octx.prefix[octx.level -1].nb_elems)
332         avio_printf(probe_out, ",\n");
333     AVP_INDENT();
334     avio_w8(probe_out, '\"');
335     json_escape_print(key);
336     avio_printf(probe_out, "\" : \"");
337     json_escape_print(value);
338     avio_w8(probe_out, '\"');
339 }
340
341 /*
342  * old-style pseudo-INI
343  */
344 static void old_print_object_header(const char *name)
345 {
346     char *str, *p;
347
348     if (!strcmp(name, "tags"))
349         return;
350
351     str = p = av_strdup(name);
352     if (!str)
353         return;
354     while (*p) {
355         *p = av_toupper(*p);
356         p++;
357     }
358
359     avio_printf(probe_out, "[%s]\n", str);
360     av_freep(&str);
361 }
362
363 static void old_print_object_footer(const char *name)
364 {
365     char *str, *p;
366
367     if (!strcmp(name, "tags"))
368         return;
369
370     str = p = av_strdup(name);
371     if (!str)
372         return;
373     while (*p) {
374         *p = av_toupper(*p);
375         p++;
376     }
377
378     avio_printf(probe_out, "[/%s]\n", str);
379     av_freep(&str);
380 }
381
382 static void old_print_string(const char *key, const char *value)
383 {
384     if (!strcmp(octx.prefix[octx.level - 1].name, "tags"))
385         avio_printf(probe_out, "TAG:");
386     ini_print_string(key, value);
387 }
388
389 /*
390  * Simple Formatter for single entries.
391  */
392
393 static void show_format_entry_integer(const char *key, int64_t value)
394 {
395     if (key && av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
396         if (nb_fmt_entries_to_show > 1)
397             avio_printf(probe_out, "%s=", key);
398         avio_printf(probe_out, "%"PRId64"\n", value);
399     }
400 }
401
402 static void show_format_entry_string(const char *key, const char *value)
403 {
404     if (key && av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
405         if (nb_fmt_entries_to_show > 1)
406             avio_printf(probe_out, "%s=", key);
407         avio_printf(probe_out, "%s\n", value);
408     }
409 }
410
411 static void show_stream_entry_header(const char *key, int value)
412 {
413     header_key = key;
414 }
415
416 static void show_stream_entry_footer(const char *key, int value)
417 {
418     header_key = NULL;
419 }
420
421 static void show_stream_entry_integer(const char *key, int64_t value)
422 {
423     if (!key)
424         key = header_key;
425
426     if (key && av_dict_get(stream_entries_to_show, key, NULL, 0)) {
427         if (nb_stream_entries_to_show > 1)
428             avio_printf(probe_out, "%s=", key);
429         avio_printf(probe_out, "%"PRId64"\n", value);
430     }
431 }
432
433 static void show_stream_entry_string(const char *key, const char *value)
434 {
435     if (key && av_dict_get(stream_entries_to_show, key, NULL, 0)) {
436         if (nb_stream_entries_to_show > 1)
437             avio_printf(probe_out, "%s=", key);
438         avio_printf(probe_out, "%s\n", value);
439     }
440 }
441
442 static void probe_group_enter(const char *name, int type)
443 {
444     int64_t count = -1;
445
446     octx.prefix =
447         av_realloc(octx.prefix, sizeof(PrintElement) * (octx.level + 1));
448
449     if (!octx.prefix || !name) {
450         fprintf(stderr, "Out of memory\n");
451         exit_program(1);
452     }
453
454     if (octx.level) {
455         PrintElement *parent = octx.prefix + octx.level -1;
456         if (parent->type == ARRAY)
457             count = parent->nb_elems;
458         parent->nb_elems++;
459     }
460
461     octx.prefix[octx.level++] = (PrintElement){name, type, count, 0};
462 }
463
464 static void probe_group_leave(void)
465 {
466     --octx.level;
467 }
468
469 static void probe_header(void)
470 {
471     if (octx.print_header)
472         octx.print_header();
473     probe_group_enter("root", OBJECT);
474 }
475
476 static void probe_footer(void)
477 {
478     if (octx.print_footer)
479         octx.print_footer();
480     probe_group_leave();
481 }
482
483
484 static void probe_array_header(const char *name, int plain_values)
485 {
486     if (octx.print_array_header)
487         octx.print_array_header(name, plain_values);
488
489     probe_group_enter(name, ARRAY);
490 }
491
492 static void probe_array_footer(const char *name, int plain_values)
493 {
494     probe_group_leave();
495     if (octx.print_array_footer)
496         octx.print_array_footer(name, plain_values);
497 }
498
499 static void probe_object_header(const char *name)
500 {
501     if (octx.print_object_header)
502         octx.print_object_header(name);
503
504     probe_group_enter(name, OBJECT);
505 }
506
507 static void probe_object_footer(const char *name)
508 {
509     probe_group_leave();
510     if (octx.print_object_footer)
511         octx.print_object_footer(name);
512 }
513
514 static void probe_int(const char *key, int64_t value)
515 {
516     octx.print_integer(key, value);
517     octx.prefix[octx.level -1].nb_elems++;
518 }
519
520 static void probe_str(const char *key, const char *value)
521 {
522     octx.print_string(key, value);
523     octx.prefix[octx.level -1].nb_elems++;
524 }
525
526 static void probe_dict(AVDictionary *dict, const char *name)
527 {
528     AVDictionaryEntry *entry = NULL;
529     if (!dict)
530         return;
531     probe_object_header(name);
532     while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) {
533         probe_str(entry->key, entry->value);
534     }
535     probe_object_footer(name);
536 }
537
538 static char *value_string(char *buf, int buf_size, double val, const char *unit)
539 {
540     if (unit == unit_second_str && use_value_sexagesimal_format) {
541         double secs;
542         int hours, mins;
543         secs  = val;
544         mins  = (int)secs / 60;
545         secs  = secs - mins * 60;
546         hours = mins / 60;
547         mins %= 60;
548         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
549     } else if (use_value_prefix) {
550         const char *prefix_string;
551         int index;
552
553         if (unit == unit_byte_str && use_byte_value_binary_prefix) {
554             index = (int) log2(val) / 10;
555             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
556             val  /= pow(2, index * 10);
557             prefix_string = binary_unit_prefixes[index];
558         } else {
559             index = (int) (log10(val)) / 3;
560             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
561             val  /= pow(10, index * 3);
562             prefix_string = decimal_unit_prefixes[index];
563         }
564         snprintf(buf, buf_size, "%.*f%s%s",
565                  index ? 3 : 0, val,
566                  prefix_string,
567                  show_value_unit ? unit : "");
568     } else {
569         snprintf(buf, buf_size, "%f%s", val, show_value_unit ? unit : "");
570     }
571
572     return buf;
573 }
574
575 static char *time_value_string(char *buf, int buf_size, int64_t val,
576                                const AVRational *time_base)
577 {
578     if (val == AV_NOPTS_VALUE) {
579         snprintf(buf, buf_size, "N/A");
580     } else {
581         value_string(buf, buf_size, val * av_q2d(*time_base), unit_second_str);
582     }
583
584     return buf;
585 }
586
587 static char *ts_value_string(char *buf, int buf_size, int64_t ts)
588 {
589     if (ts == AV_NOPTS_VALUE) {
590         snprintf(buf, buf_size, "N/A");
591     } else {
592         snprintf(buf, buf_size, "%"PRId64, ts);
593     }
594
595     return buf;
596 }
597
598 static char *rational_string(char *buf, int buf_size, const char *sep,
599                              const AVRational *rat)
600 {
601     snprintf(buf, buf_size, "%d%s%d", rat->num, sep, rat->den);
602     return buf;
603 }
604
605 static char *tag_string(char *buf, int buf_size, int tag)
606 {
607     snprintf(buf, buf_size, "0x%04x", tag);
608     return buf;
609 }
610
611 static void show_packet(AVFormatContext *fmt_ctx, AVPacket *pkt)
612 {
613     char val_str[128];
614     AVStream *st = fmt_ctx->streams[pkt->stream_index];
615
616     probe_object_header("packet");
617     probe_str("codec_type", media_type_string(st->codecpar->codec_type));
618     probe_int("stream_index", pkt->stream_index);
619     probe_str("pts", ts_value_string(val_str, sizeof(val_str), pkt->pts));
620     probe_str("pts_time", time_value_string(val_str, sizeof(val_str),
621                                                pkt->pts, &st->time_base));
622     probe_str("dts", ts_value_string(val_str, sizeof(val_str), pkt->dts));
623     probe_str("dts_time", time_value_string(val_str, sizeof(val_str),
624                                                pkt->dts, &st->time_base));
625     probe_str("duration", ts_value_string(val_str, sizeof(val_str),
626                                              pkt->duration));
627     probe_str("duration_time", time_value_string(val_str, sizeof(val_str),
628                                                     pkt->duration,
629                                                     &st->time_base));
630     probe_str("size", value_string(val_str, sizeof(val_str),
631                                       pkt->size, unit_byte_str));
632     probe_int("pos", pkt->pos);
633     probe_str("flags", pkt->flags & AV_PKT_FLAG_KEY ? "K" : "_");
634     probe_object_footer("packet");
635 }
636
637 static void show_packets(InputFile *ifile)
638 {
639     AVFormatContext *fmt_ctx = ifile->fmt_ctx;
640     AVPacket pkt;
641
642     av_init_packet(&pkt);
643     probe_array_header("packets", 0);
644     while (!av_read_frame(fmt_ctx, &pkt)) {
645         show_packet(fmt_ctx, &pkt);
646         av_packet_unref(&pkt);
647     }
648     probe_array_footer("packets", 0);
649 }
650
651 static void show_stream(InputFile *ifile, InputStream *ist)
652 {
653     AVFormatContext *fmt_ctx = ifile->fmt_ctx;
654     AVStream *stream = ist->st;
655     AVCodecParameters *par;
656     AVCodecContext *dec_ctx;
657     const AVCodecDescriptor *codec_desc;
658     const char *profile;
659     char val_str[128];
660     AVRational display_aspect_ratio, *sar = NULL;
661     const AVPixFmtDescriptor *desc;
662
663     probe_object_header("stream");
664
665     probe_int("index", stream->index);
666
667     par     = stream->codecpar;
668     dec_ctx = ist->dec_ctx;
669     codec_desc = avcodec_descriptor_get(par->codec_id);
670     if (codec_desc) {
671         probe_str("codec_name", codec_desc->name);
672         probe_str("codec_long_name", codec_desc->long_name);
673     } else {
674         probe_str("codec_name", "unknown");
675     }
676
677     probe_str("codec_type", media_type_string(par->codec_type));
678
679     /* print AVI/FourCC tag */
680     av_get_codec_tag_string(val_str, sizeof(val_str), par->codec_tag);
681     probe_str("codec_tag_string", val_str);
682     probe_str("codec_tag", tag_string(val_str, sizeof(val_str),
683                                       par->codec_tag));
684
685     /* print profile, if there is one */
686     profile = avcodec_profile_name(par->codec_id, par->profile);
687     if (profile)
688         probe_str("profile", profile);
689
690     switch (par->codec_type) {
691     case AVMEDIA_TYPE_VIDEO:
692         probe_int("width",  par->width);
693         probe_int("height", par->height);
694         if (dec_ctx) {
695             probe_int("coded_width",  dec_ctx->coded_width);
696             probe_int("coded_height", dec_ctx->coded_height);
697             probe_int("has_b_frames", dec_ctx->has_b_frames);
698         }
699         if (dec_ctx && dec_ctx->sample_aspect_ratio.num)
700             sar = &dec_ctx->sample_aspect_ratio;
701         else if (par->sample_aspect_ratio.num)
702             sar = &par->sample_aspect_ratio;
703         else if (stream->sample_aspect_ratio.num)
704             sar = &stream->sample_aspect_ratio;
705
706         if (sar) {
707             probe_str("sample_aspect_ratio",
708                       rational_string(val_str, sizeof(val_str), ":", sar));
709             av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
710                       par->width  * sar->num, par->height * sar->den,
711                       1024*1024);
712             probe_str("display_aspect_ratio",
713                       rational_string(val_str, sizeof(val_str), ":",
714                       &display_aspect_ratio));
715         }
716         desc = av_pix_fmt_desc_get(par->format);
717         probe_str("pix_fmt", desc ? desc->name : "unknown");
718         probe_int("level", par->level);
719
720         probe_str("color_range", av_color_range_name    (par->color_range));
721         probe_str("color_space", av_color_space_name    (par->color_space));
722         probe_str("color_trc",   av_color_transfer_name (par->color_trc));
723         probe_str("color_pri",   av_color_primaries_name(par->color_primaries));
724         probe_str("chroma_loc", av_chroma_location_name (par->chroma_location));
725         break;
726
727     case AVMEDIA_TYPE_AUDIO:
728         probe_str("sample_rate",
729                   value_string(val_str, sizeof(val_str),
730                                par->sample_rate,
731                                unit_hertz_str));
732         probe_int("channels", par->channels);
733         probe_int("bits_per_sample",
734                   av_get_bits_per_sample(par->codec_id));
735         break;
736     }
737
738     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
739         probe_int("id", stream->id);
740     probe_str("avg_frame_rate",
741               rational_string(val_str, sizeof(val_str), "/",
742               &stream->avg_frame_rate));
743
744     if (par->bit_rate)
745         probe_str("bit_rate",
746                   value_string(val_str, sizeof(val_str),
747                                par->bit_rate, unit_bit_per_second_str));
748     probe_str("time_base",
749               rational_string(val_str, sizeof(val_str), "/",
750               &stream->time_base));
751     probe_str("start_time",
752               time_value_string(val_str, sizeof(val_str),
753                                 stream->start_time, &stream->time_base));
754     probe_str("duration",
755               time_value_string(val_str, sizeof(val_str),
756                                 stream->duration, &stream->time_base));
757     if (stream->nb_frames)
758         probe_int("nb_frames", stream->nb_frames);
759
760     probe_dict(stream->metadata, "tags");
761
762     if (stream->nb_side_data) {
763         int i, j;
764
765         probe_object_header("sidedata");
766         for (i = 0; i < stream->nb_side_data; i++) {
767             const AVPacketSideData* sd = &stream->side_data[i];
768             AVStereo3D *stereo;
769
770             switch (sd->type) {
771             case AV_PKT_DATA_DISPLAYMATRIX:
772                 probe_object_header("displaymatrix");
773                 probe_array_header("matrix", 1);
774                 for (j = 0; j < 9; j++)
775                     probe_int(NULL, ((int32_t *)sd->data)[j]);
776                 probe_array_footer("matrix", 1);
777                 probe_int("rotation",
778                           av_display_rotation_get((int32_t *)sd->data));
779                 probe_object_footer("displaymatrix");
780                 break;
781             case AV_PKT_DATA_STEREO3D:
782                 stereo = (AVStereo3D *)sd->data;
783                 probe_object_header("stereo3d");
784                 probe_str("type", av_stereo3d_type_name(stereo->type));
785                 probe_int("inverted",
786                           !!(stereo->flags & AV_STEREO3D_FLAG_INVERT));
787                 probe_object_footer("stereo3d");
788                 break;
789             }
790         }
791         probe_object_footer("sidedata");
792     }
793
794     probe_object_footer("stream");
795 }
796
797 static void show_format(InputFile *ifile)
798 {
799     AVFormatContext *fmt_ctx = ifile->fmt_ctx;
800     char val_str[128];
801     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
802
803     probe_object_header("format");
804     probe_str("filename",         fmt_ctx->filename);
805     probe_int("nb_streams",       fmt_ctx->nb_streams);
806     probe_str("format_name",      fmt_ctx->iformat->name);
807     probe_str("format_long_name", fmt_ctx->iformat->long_name);
808     probe_str("start_time",
809                        time_value_string(val_str, sizeof(val_str),
810                                          fmt_ctx->start_time, &AV_TIME_BASE_Q));
811     probe_str("duration",
812                        time_value_string(val_str, sizeof(val_str),
813                                          fmt_ctx->duration, &AV_TIME_BASE_Q));
814     probe_str("size",
815                        size >= 0 ? value_string(val_str, sizeof(val_str),
816                                                 size, unit_byte_str)
817                                   : "unknown");
818     probe_str("bit_rate",
819                        value_string(val_str, sizeof(val_str),
820                                     fmt_ctx->bit_rate, unit_bit_per_second_str));
821
822     probe_dict(fmt_ctx->metadata, "tags");
823
824     probe_object_footer("format");
825 }
826
827 static int open_input_file(InputFile *ifile, const char *filename)
828 {
829     int err, i;
830     AVFormatContext *fmt_ctx = NULL;
831     AVDictionaryEntry *t;
832
833     if ((err = avformat_open_input(&fmt_ctx, filename,
834                                    iformat, &format_opts)) < 0) {
835         print_error(filename, err);
836         return err;
837     }
838     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
839         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
840         return AVERROR_OPTION_NOT_FOUND;
841     }
842
843
844     /* fill the streams in the format context */
845     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
846         print_error(filename, err);
847         return err;
848     }
849
850     av_dump_format(fmt_ctx, 0, filename, 0);
851
852     ifile->streams = av_mallocz_array(fmt_ctx->nb_streams,
853                                       sizeof(*ifile->streams));
854     if (!ifile->streams)
855         exit(1);
856     ifile->nb_streams = fmt_ctx->nb_streams;
857
858     /* bind a decoder to each input stream */
859     for (i = 0; i < fmt_ctx->nb_streams; i++) {
860         InputStream *ist = &ifile->streams[i];
861         AVStream *stream = fmt_ctx->streams[i];
862         AVCodec *codec;
863
864         ist->st = stream;
865
866         if (stream->codecpar->codec_id == AV_CODEC_ID_PROBE) {
867             fprintf(stderr, "Failed to probe codec for input stream %d\n",
868                     stream->index);
869             continue;
870         }
871
872         codec = avcodec_find_decoder(stream->codecpar->codec_id);
873         if (!codec) {
874             fprintf(stderr,
875                     "Unsupported codec with id %d for input stream %d\n",
876                     stream->codecpar->codec_id, stream->index);
877             continue;
878         }
879
880         ist->dec_ctx = avcodec_alloc_context3(codec);
881         if (!ist->dec_ctx)
882             exit(1);
883
884         err = avcodec_parameters_to_context(ist->dec_ctx, stream->codecpar);
885         if (err < 0)
886             exit(1);
887
888         err = avcodec_open2(ist->dec_ctx, NULL, NULL);
889         if (err < 0) {
890             fprintf(stderr, "Error while opening codec for input stream %d\n",
891                     stream->index);
892             exit(1);
893
894         }
895     }
896
897     ifile->fmt_ctx = fmt_ctx;
898     return 0;
899 }
900
901 static void close_input_file(InputFile *ifile)
902 {
903     int i;
904
905     /* close decoder for each stream */
906     for (i = 0; i < ifile->nb_streams; i++) {
907         InputStream *ist = &ifile->streams[i];
908
909         avcodec_free_context(&ist->dec_ctx);
910     }
911
912     av_freep(&ifile->streams);
913     ifile->nb_streams = 0;
914
915     avformat_close_input(&ifile->fmt_ctx);
916 }
917
918 static int probe_file(const char *filename)
919 {
920     InputFile ifile;
921     int ret, i;
922
923     ret = open_input_file(&ifile, filename);
924     if (ret < 0)
925         return ret;
926
927     if (do_show_format)
928         show_format(&ifile);
929
930     if (do_show_streams) {
931         probe_array_header("streams", 0);
932         for (i = 0; i < ifile.nb_streams; i++)
933             show_stream(&ifile, &ifile.streams[i]);
934         probe_array_footer("streams", 0);
935     }
936
937     if (do_show_packets)
938         show_packets(&ifile);
939
940     close_input_file(&ifile);
941     return 0;
942 }
943
944 static void show_usage(void)
945 {
946     printf("Simple multimedia streams analyzer\n");
947     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
948     printf("\n");
949 }
950
951 static int opt_format(void *optctx, const char *opt, const char *arg)
952 {
953     iformat = av_find_input_format(arg);
954     if (!iformat) {
955         fprintf(stderr, "Unknown input format: %s\n", arg);
956         return AVERROR(EINVAL);
957     }
958     return 0;
959 }
960
961 static int opt_output_format(void *optctx, const char *opt, const char *arg)
962 {
963
964     if (!strcmp(arg, "json")) {
965         octx.print_header        = json_print_header;
966         octx.print_footer        = json_print_footer;
967         octx.print_array_header  = json_print_array_header;
968         octx.print_array_footer  = json_print_array_footer;
969         octx.print_object_header = json_print_object_header;
970         octx.print_object_footer = json_print_object_footer;
971
972         octx.print_integer = json_print_integer;
973         octx.print_string  = json_print_string;
974     } else if (!strcmp(arg, "ini")) {
975         octx.print_header        = ini_print_header;
976         octx.print_footer        = ini_print_footer;
977         octx.print_array_header  = ini_print_array_header;
978         octx.print_array_footer  = ini_print_array_footer;
979         octx.print_object_header = ini_print_object_header;
980
981         octx.print_integer = ini_print_integer;
982         octx.print_string  = ini_print_string;
983     } else if (!strcmp(arg, "old")) {
984         octx.print_header        = NULL;
985         octx.print_object_header = old_print_object_header;
986         octx.print_object_footer = old_print_object_footer;
987
988         octx.print_string        = old_print_string;
989     } else {
990         av_log(NULL, AV_LOG_ERROR, "Unsupported formatter %s\n", arg);
991         return AVERROR(EINVAL);
992     }
993     return 0;
994 }
995
996 static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
997 {
998     do_show_format = 1;
999     nb_fmt_entries_to_show++;
1000     octx.print_header        = NULL;
1001     octx.print_footer        = NULL;
1002     octx.print_array_header  = NULL;
1003     octx.print_array_footer  = NULL;
1004     octx.print_object_header = NULL;
1005     octx.print_object_footer = NULL;
1006
1007     octx.print_integer = show_format_entry_integer;
1008     octx.print_string  = show_format_entry_string;
1009     av_dict_set(&fmt_entries_to_show, arg, "", 0);
1010     return 0;
1011 }
1012
1013 static int opt_show_stream_entry(void *optctx, const char *opt, const char *arg)
1014 {
1015     do_show_streams = 1;
1016     nb_stream_entries_to_show++;
1017     octx.print_header        = NULL;
1018     octx.print_footer        = NULL;
1019     octx.print_array_header  = show_stream_entry_header;
1020     octx.print_array_footer  = show_stream_entry_footer;
1021     octx.print_object_header = NULL;
1022     octx.print_object_footer = NULL;
1023
1024     octx.print_integer = show_stream_entry_integer;
1025     octx.print_string  = show_stream_entry_string;
1026     av_dict_set(&stream_entries_to_show, arg, "", 0);
1027     return 0;
1028 }
1029
1030 static void opt_input_file(void *optctx, const char *arg)
1031 {
1032     if (input_filename) {
1033         fprintf(stderr,
1034                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1035                 arg, input_filename);
1036         exit_program(1);
1037     }
1038     if (!strcmp(arg, "-"))
1039         arg = "pipe:";
1040     input_filename = arg;
1041 }
1042
1043 void show_help_default(const char *opt, const char *arg)
1044 {
1045     av_log_set_callback(log_callback_help);
1046     show_usage();
1047     show_help_options(options, "Main options:", 0, 0, 0);
1048     printf("\n");
1049     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1050 }
1051
1052 static int opt_pretty(void *optctx, const char *opt, const char *arg)
1053 {
1054     show_value_unit              = 1;
1055     use_value_prefix             = 1;
1056     use_byte_value_binary_prefix = 1;
1057     use_value_sexagesimal_format = 1;
1058     return 0;
1059 }
1060
1061 static const OptionDef real_options[] = {
1062 #include "cmdutils_common_opts.h"
1063     { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
1064     { "of", HAS_ARG, {.func_arg = opt_output_format}, "output the document either as ini or json", "output_format" },
1065     { "unit", OPT_BOOL, {&show_value_unit},
1066       "show unit of the displayed values" },
1067     { "prefix", OPT_BOOL, {&use_value_prefix},
1068       "use SI prefixes for the displayed values" },
1069     { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
1070       "use binary prefixes for byte units" },
1071     { "sexagesimal", OPT_BOOL,  {&use_value_sexagesimal_format},
1072       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1073     { "pretty", 0, {.func_arg = opt_pretty},
1074       "prettify the format of displayed values, make it more human readable" },
1075     { "show_format",  OPT_BOOL, {&do_show_format} , "show format/container info" },
1076     { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
1077       "show a particular entry from the format/container info", "entry" },
1078     { "show_packets", OPT_BOOL, {&do_show_packets}, "show packets info" },
1079     { "show_streams", OPT_BOOL, {&do_show_streams}, "show streams info" },
1080     { "show_stream_entry", HAS_ARG, {.func_arg = opt_show_stream_entry},
1081       "show a particular entry from all streams", "entry" },
1082     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default},
1083       "generic catch all option", "" },
1084     { NULL, },
1085 };
1086
1087 static int probe_buf_write(void *opaque, uint8_t *buf, int buf_size)
1088 {
1089     printf("%.*s", buf_size, buf);
1090     return 0;
1091 }
1092
1093 #define AVP_BUFFSIZE 4096
1094
1095 int main(int argc, char **argv)
1096 {
1097     int ret;
1098     uint8_t *buffer = av_malloc(AVP_BUFFSIZE);
1099
1100     if (!buffer)
1101         exit(1);
1102
1103     register_exit(avprobe_cleanup);
1104
1105     options = real_options;
1106     parse_loglevel(argc, argv, options);
1107     av_register_all();
1108     avformat_network_init();
1109     init_opts();
1110 #if CONFIG_AVDEVICE
1111     avdevice_register_all();
1112 #endif
1113
1114     show_banner();
1115
1116     octx.print_header = ini_print_header;
1117     octx.print_footer = ini_print_footer;
1118
1119     octx.print_array_header = ini_print_array_header;
1120     octx.print_array_footer = ini_print_array_footer;
1121     octx.print_object_header = ini_print_object_header;
1122
1123     octx.print_integer = ini_print_integer;
1124     octx.print_string = ini_print_string;
1125
1126     parse_options(NULL, argc, argv, options, opt_input_file);
1127
1128     if (!input_filename) {
1129         show_usage();
1130         fprintf(stderr, "You have to specify one input file.\n");
1131         fprintf(stderr,
1132                 "Use -h to get full help or, even better, run 'man %s'.\n",
1133                 program_name);
1134         exit_program(1);
1135     }
1136
1137     probe_out = avio_alloc_context(buffer, AVP_BUFFSIZE, 1, NULL, NULL,
1138                                  probe_buf_write, NULL);
1139     if (!probe_out)
1140         exit_program(1);
1141
1142     probe_header();
1143     ret = probe_file(input_filename);
1144     probe_footer();
1145     avio_flush(probe_out);
1146     av_freep(&probe_out);
1147     av_freep(&buffer);
1148     uninit_opts();
1149     avformat_network_deinit();
1150
1151     return ret;
1152 }