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