]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
ffprobe: change formatting logic in the JSON writer
[ffmpeg] / ffprobe.c
1 /*
2  * Copyright (c) 2007-2010 Stefano Sabatini
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * simple media prober based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27
28 #include "libavformat/avformat.h"
29 #include "libavcodec/avcodec.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/dict.h"
34 #include "libavdevice/avdevice.h"
35 #include "cmdutils.h"
36
37 const char program_name[] = "ffprobe";
38 const int program_birth_year = 2007;
39
40 static int do_show_error   = 0;
41 static int do_show_format  = 0;
42 static int do_show_frames  = 0;
43 static int do_show_packets = 0;
44 static int do_show_streams = 0;
45
46 static int show_value_unit              = 0;
47 static int use_value_prefix             = 0;
48 static int use_byte_value_binary_prefix = 0;
49 static int use_value_sexagesimal_format = 0;
50 static int show_private_data            = 1;
51
52 static char *print_format;
53
54 static const OptionDef options[];
55
56 /* FFprobe context */
57 static const char *input_filename;
58 static AVInputFormat *iformat = NULL;
59
60 static const char *binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
61 static const char *decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
62
63 static const char *unit_second_str          = "s"    ;
64 static const char *unit_hertz_str           = "Hz"   ;
65 static const char *unit_byte_str            = "byte" ;
66 static const char *unit_bit_per_second_str  = "bit/s";
67
68 void av_noreturn exit_program(int ret)
69 {
70     exit(ret);
71 }
72
73 struct unit_value {
74     union { double d; int i; } val;
75     const char *unit;
76 };
77
78 static char *value_string(char *buf, int buf_size, struct unit_value uv)
79 {
80     double vald;
81     int show_float = 0;
82
83     if (uv.unit == unit_second_str) {
84         vald = uv.val.d;
85         show_float = 1;
86     } else {
87         vald = uv.val.i;
88     }
89
90     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
91         double secs;
92         int hours, mins;
93         secs  = vald;
94         mins  = (int)secs / 60;
95         secs  = secs - mins * 60;
96         hours = mins / 60;
97         mins %= 60;
98         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
99     } else if (use_value_prefix) {
100         const char *prefix_string;
101         int index, l;
102
103         if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
104             index = (int) (log(vald)/log(2)) / 10;
105             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
106             vald /= pow(2, index*10);
107             prefix_string = binary_unit_prefixes[index];
108         } else {
109             index = (int) (log10(vald)) / 3;
110             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
111             vald /= pow(10, index*3);
112             prefix_string = decimal_unit_prefixes[index];
113         }
114
115         if (show_float || vald != (int)vald) l = snprintf(buf, buf_size, "%.3f", vald);
116         else                                 l = snprintf(buf, buf_size, "%d",   (int)vald);
117         snprintf(buf+l, buf_size-l, "%s%s%s", prefix_string || show_value_unit ? " " : "",
118                  prefix_string, show_value_unit ? uv.unit : "");
119     } else {
120         int l;
121
122         if (show_float) l = snprintf(buf, buf_size, "%.3f", vald);
123         else            l = snprintf(buf, buf_size, "%d",   (int)vald);
124         snprintf(buf+l, buf_size-l, "%s%s", show_value_unit ? " " : "",
125                  show_value_unit ? uv.unit : "");
126     }
127
128     return buf;
129 }
130
131 /* WRITERS API */
132
133 typedef struct WriterContext WriterContext;
134
135 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
136 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
137
138 typedef struct Writer {
139     int priv_size;                  ///< private size for the writer context
140     const char *name;
141
142     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
143     void (*uninit)(WriterContext *wctx);
144
145     void (*print_header)(WriterContext *ctx);
146     void (*print_footer)(WriterContext *ctx);
147
148     void (*print_chapter_header)(WriterContext *wctx, const char *);
149     void (*print_chapter_footer)(WriterContext *wctx, const char *);
150     void (*print_section_header)(WriterContext *wctx, const char *);
151     void (*print_section_footer)(WriterContext *wctx, const char *);
152     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
153     void (*print_string)        (WriterContext *wctx, const char *, const char *);
154     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
155     int flags;                  ///< a combination or WRITER_FLAG_*
156 } Writer;
157
158 struct WriterContext {
159     const AVClass *class;           ///< class of the writer
160     const Writer *writer;           ///< the Writer of which this is an instance
161     char *name;                     ///< name of this writer instance
162     void *priv;                     ///< private data for use by the filter
163     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
164     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
165     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
166 };
167
168 static const char *writer_get_name(void *p)
169 {
170     WriterContext *wctx = p;
171     return wctx->writer->name;
172 }
173
174 static const AVClass writer_class = {
175     "Writer",
176     writer_get_name,
177     NULL,
178     LIBAVUTIL_VERSION_INT,
179 };
180
181 static void writer_close(WriterContext **wctx)
182 {
183     if (!*wctx)
184         return;
185
186     if ((*wctx)->writer->uninit)
187         (*wctx)->writer->uninit(*wctx);
188     av_freep(&((*wctx)->priv));
189     av_freep(wctx);
190 }
191
192 static int writer_open(WriterContext **wctx, const Writer *writer,
193                        const char *args, void *opaque)
194 {
195     int ret = 0;
196
197     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
198         ret = AVERROR(ENOMEM);
199         goto fail;
200     }
201
202     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
203         ret = AVERROR(ENOMEM);
204         goto fail;
205     }
206
207     (*wctx)->class = &writer_class;
208     (*wctx)->writer = writer;
209     if ((*wctx)->writer->init)
210         ret = (*wctx)->writer->init(*wctx, args, opaque);
211     if (ret < 0)
212         goto fail;
213
214     return 0;
215
216 fail:
217     writer_close(wctx);
218     return ret;
219 }
220
221 static inline void writer_print_header(WriterContext *wctx)
222 {
223     if (wctx->writer->print_header)
224         wctx->writer->print_header(wctx);
225     wctx->nb_chapter = 0;
226 }
227
228 static inline void writer_print_footer(WriterContext *wctx)
229 {
230     if (wctx->writer->print_footer)
231         wctx->writer->print_footer(wctx);
232 }
233
234 static inline void writer_print_chapter_header(WriterContext *wctx,
235                                                const char *chapter)
236 {
237     if (wctx->writer->print_chapter_header)
238         wctx->writer->print_chapter_header(wctx, chapter);
239     wctx->nb_section = 0;
240 }
241
242 static inline void writer_print_chapter_footer(WriterContext *wctx,
243                                                const char *chapter)
244 {
245     if (wctx->writer->print_chapter_footer)
246         wctx->writer->print_chapter_footer(wctx, chapter);
247     wctx->nb_chapter++;
248 }
249
250 static inline void writer_print_section_header(WriterContext *wctx,
251                                                const char *section)
252 {
253     if (wctx->writer->print_section_header)
254         wctx->writer->print_section_header(wctx, section);
255     wctx->nb_item = 0;
256 }
257
258 static inline void writer_print_section_footer(WriterContext *wctx,
259                                                const char *section)
260 {
261     if (wctx->writer->print_section_footer)
262         wctx->writer->print_section_footer(wctx, section);
263     wctx->nb_section++;
264 }
265
266 static inline void writer_print_integer(WriterContext *wctx,
267                                         const char *key, long long int val)
268 {
269     wctx->writer->print_integer(wctx, key, val);
270     wctx->nb_item++;
271 }
272
273 static inline void writer_print_string(WriterContext *wctx,
274                                        const char *key, const char *val, int opt)
275 {
276     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
277         return;
278     wctx->writer->print_string(wctx, key, val);
279     wctx->nb_item++;
280 }
281
282 static void writer_print_time(WriterContext *wctx, const char *key,
283                               int64_t ts, const AVRational *time_base)
284 {
285     char buf[128];
286
287     if (ts == AV_NOPTS_VALUE) {
288         writer_print_string(wctx, key, "N/A", 1);
289     } else {
290         double d = ts * av_q2d(*time_base);
291         value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
292         writer_print_string(wctx, key, buf, 0);
293     }
294 }
295
296 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts)
297 {
298     if (ts == AV_NOPTS_VALUE) {
299         writer_print_string(wctx, key, "N/A", 1);
300     } else {
301         writer_print_integer(wctx, key, ts);
302     }
303 }
304
305 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
306 {
307     wctx->writer->show_tags(wctx, dict);
308 }
309
310 #define MAX_REGISTERED_WRITERS_NB 64
311
312 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
313
314 static int writer_register(const Writer *writer)
315 {
316     static int next_registered_writer_idx = 0;
317
318     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
319         return AVERROR(ENOMEM);
320
321     registered_writers[next_registered_writer_idx++] = writer;
322     return 0;
323 }
324
325 static const Writer *writer_get_by_name(const char *name)
326 {
327     int i;
328
329     for (i = 0; registered_writers[i]; i++)
330         if (!strcmp(registered_writers[i]->name, name))
331             return registered_writers[i];
332
333     return NULL;
334 }
335
336 /* Print helpers */
337
338 struct print_buf {
339     char *s;
340     int len;
341 };
342
343 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
344 {
345     va_list va;
346     int len;
347
348     va_start(va, fmt);
349     len = vsnprintf(NULL, 0, fmt, va);
350     va_end(va);
351     if (len < 0)
352         goto fail;
353
354     if (pbuf->len < len) {
355         char *p = av_realloc(pbuf->s, len + 1);
356         if (!p)
357             goto fail;
358         pbuf->s   = p;
359         pbuf->len = len;
360     }
361
362     va_start(va, fmt);
363     len = vsnprintf(pbuf->s, len + 1, fmt, va);
364     va_end(va);
365     if (len < 0)
366         goto fail;
367     return pbuf->s;
368
369 fail:
370     av_freep(&pbuf->s);
371     pbuf->len = 0;
372     return NULL;
373 }
374
375 #define ESCAPE_INIT_BUF_SIZE 256
376
377 #define ESCAPE_CHECK_SIZE(src, size, max_size)                          \
378     if (size > max_size) {                                              \
379         char buf[64];                                                   \
380         snprintf(buf, sizeof(buf), "%s", src);                          \
381         av_log(log_ctx, AV_LOG_WARNING,                                 \
382                "String '%s...' with is too big\n", buf);                \
383         return "FFPROBE_TOO_BIG_STRING";                                \
384     }
385
386 #define ESCAPE_REALLOC_BUF(dst_size_p, dst_p, src, size)                \
387     if (*dst_size_p < size) {                                           \
388         char *q = av_realloc(*dst_p, size);                             \
389         if (!q) {                                                       \
390             char buf[64];                                               \
391             snprintf(buf, sizeof(buf), "%s", src);                      \
392             av_log(log_ctx, AV_LOG_WARNING,                             \
393                    "String '%s...' could not be escaped\n", buf);       \
394             return "FFPROBE_THIS_STRING_COULD_NOT_BE_ESCAPED";          \
395         }                                                               \
396         *dst_size_p = size;                                             \
397         *dst = q;                                                       \
398     }
399
400 /* WRITERS */
401
402 /* Default output */
403
404 static void default_print_footer(WriterContext *wctx)
405 {
406     printf("\n");
407 }
408
409 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
410 {
411     if (wctx->nb_chapter)
412         printf("\n");
413 }
414
415 /* lame uppercasing routine, assumes the string is lower case ASCII */
416 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
417 {
418     int i;
419     for (i = 0; src[i] && i < dst_size-1; i++)
420         dst[i] = src[i]-32;
421     dst[i] = 0;
422     return dst;
423 }
424
425 static void default_print_section_header(WriterContext *wctx, const char *section)
426 {
427     char buf[32];
428
429     if (wctx->nb_section)
430         printf("\n");
431     printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
432 }
433
434 static void default_print_section_footer(WriterContext *wctx, const char *section)
435 {
436     char buf[32];
437
438     printf("[/%s]", upcase_string(buf, sizeof(buf), section));
439 }
440
441 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
442 {
443     printf("%s=%s\n", key, value);
444 }
445
446 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
447 {
448     printf("%s=%lld\n", key, value);
449 }
450
451 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
452 {
453     AVDictionaryEntry *tag = NULL;
454     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
455         printf("TAG:");
456         writer_print_string(wctx, tag->key, tag->value, 0);
457     }
458 }
459
460 static const Writer default_writer = {
461     .name                  = "default",
462     .print_footer          = default_print_footer,
463     .print_chapter_header  = default_print_chapter_header,
464     .print_section_header  = default_print_section_header,
465     .print_section_footer  = default_print_section_footer,
466     .print_integer         = default_print_int,
467     .print_string          = default_print_str,
468     .show_tags             = default_show_tags,
469     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
470 };
471
472 /* Compact output */
473
474 /**
475  * Escape \n, \r, \\ and sep characters contained in s, and print the
476  * resulting string.
477  */
478 static const char *c_escape_str(char **dst, size_t *dst_size,
479                                 const char *src, const char sep, void *log_ctx)
480 {
481     const char *p;
482     char *q;
483     size_t size = 1;
484
485     /* precompute size */
486     for (p = src; *p; p++, size++) {
487         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-2);
488         if (*p == '\n' || *p == '\r' || *p == '\\')
489             size++;
490     }
491
492     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
493
494     q = *dst;
495     for (p = src; *p; p++) {
496         switch (*src) {
497         case '\n': *q++ = '\\'; *q++ = 'n';  break;
498         case '\r': *q++ = '\\'; *q++ = 'r';  break;
499         case '\\': *q++ = '\\'; *q++ = '\\'; break;
500         default:
501             if (*p == sep)
502                 *q++ = '\\';
503             *q++ = *p;
504         }
505     }
506     *q = 0;
507     return *dst;
508 }
509
510 /**
511  * Quote fields containing special characters, check RFC4180.
512  */
513 static const char *csv_escape_str(char **dst, size_t *dst_size,
514                                   const char *src, const char sep, void *log_ctx)
515 {
516     const char *p;
517     char *q;
518     size_t size = 1;
519     int quote = 0;
520
521     /* precompute size */
522     for (p = src; *p; p++, size++) {
523         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-4);
524         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
525             if (!quote) {
526                 quote = 1;
527                 size += 2;
528             }
529         if (*p == '"')
530             size++;
531     }
532
533     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
534
535     q = *dst;
536     p = src;
537     if (quote)
538         *q++ = '\"';
539     while (*p) {
540         if (*p == '"')
541             *q++ = '\"';
542         *q++ = *p++;
543     }
544     if (quote)
545         *q++ = '\"';
546     *q = 0;
547
548     return *dst;
549 }
550
551 static const char *none_escape_str(char **dst, size_t *dst_size,
552                                    const char *src, const char sep, void *log_ctx)
553 {
554     return src;
555 }
556
557 typedef struct CompactContext {
558     const AVClass *class;
559     char *item_sep_str;
560     char item_sep;
561     int nokey;
562     char  *buf;
563     size_t buf_size;
564     char *escape_mode_str;
565     const char * (*escape_str)(char **dst, size_t *dst_size,
566                                const char *src, const char sep, void *log_ctx);
567 } CompactContext;
568
569 #define OFFSET(x) offsetof(CompactContext, x)
570
571 static const AVOption compact_options[]= {
572     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
573     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
574     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
575     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
576     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
577     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
578     {NULL},
579 };
580
581 static const char *compact_get_name(void *ctx)
582 {
583     return "compact";
584 }
585
586 static const AVClass compact_class = {
587     "CompactContext",
588     compact_get_name,
589     compact_options
590 };
591
592 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
593 {
594     CompactContext *compact = wctx->priv;
595     int err;
596
597     compact->class = &compact_class;
598     av_opt_set_defaults(compact);
599
600     if (args &&
601         (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
602         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
603         return err;
604     }
605     if (strlen(compact->item_sep_str) != 1) {
606         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
607                compact->item_sep_str);
608         return AVERROR(EINVAL);
609     }
610     compact->item_sep = compact->item_sep_str[0];
611
612     compact->buf_size = ESCAPE_INIT_BUF_SIZE;
613     if (!(compact->buf = av_malloc(compact->buf_size)))
614         return AVERROR(ENOMEM);
615
616     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
617     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
618     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
619     else {
620         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
621         return AVERROR(EINVAL);
622     }
623
624     return 0;
625 }
626
627 static av_cold void compact_uninit(WriterContext *wctx)
628 {
629     CompactContext *compact = wctx->priv;
630
631     av_freep(&compact->item_sep_str);
632     av_freep(&compact->buf);
633     av_freep(&compact->escape_mode_str);
634 }
635
636 static void compact_print_section_header(WriterContext *wctx, const char *section)
637 {
638     CompactContext *compact = wctx->priv;
639
640     printf("%s%c", section, compact->item_sep);
641 }
642
643 static void compact_print_section_footer(WriterContext *wctx, const char *section)
644 {
645     printf("\n");
646 }
647
648 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
649 {
650     CompactContext *compact = wctx->priv;
651
652     if (wctx->nb_item) printf("%c", compact->item_sep);
653     if (!compact->nokey)
654         printf("%s=", key);
655     printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
656                                      value, compact->item_sep, wctx));
657 }
658
659 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
660 {
661     CompactContext *compact = wctx->priv;
662
663     if (wctx->nb_item) printf("%c", compact->item_sep);
664     if (!compact->nokey)
665         printf("%s=", key);
666     printf("%lld", value);
667 }
668
669 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
670 {
671     CompactContext *compact = wctx->priv;
672     AVDictionaryEntry *tag = NULL;
673
674     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
675         if (wctx->nb_item) printf("%c", compact->item_sep);
676         if (!compact->nokey)
677             printf("tag:%s=", compact->escape_str(&compact->buf, &compact->buf_size,
678                                                   tag->key, compact->item_sep, wctx));
679         printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
680                                          tag->value, compact->item_sep, wctx));
681     }
682 }
683
684 static const Writer compact_writer = {
685     .name                 = "compact",
686     .priv_size            = sizeof(CompactContext),
687     .init                 = compact_init,
688     .uninit               = compact_uninit,
689     .print_section_header = compact_print_section_header,
690     .print_section_footer = compact_print_section_footer,
691     .print_integer        = compact_print_int,
692     .print_string         = compact_print_str,
693     .show_tags            = compact_show_tags,
694     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
695 };
696
697 /* CSV output */
698
699 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
700 {
701     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
702 }
703
704 static const Writer csv_writer = {
705     .name                 = "csv",
706     .priv_size            = sizeof(CompactContext),
707     .init                 = csv_init,
708     .uninit               = compact_uninit,
709     .print_section_header = compact_print_section_header,
710     .print_section_footer = compact_print_section_footer,
711     .print_integer        = compact_print_int,
712     .print_string         = compact_print_str,
713     .show_tags            = compact_show_tags,
714     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
715 };
716
717 /* JSON output */
718
719 typedef struct {
720     int multiple_entries; ///< tells if the given chapter requires multiple entries
721     char *buf;
722     size_t buf_size;
723     int print_packets_and_frames;
724     int indent_level;
725 } JSONContext;
726
727 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
728 {
729     JSONContext *json = wctx->priv;
730
731     json->buf_size = ESCAPE_INIT_BUF_SIZE;
732     if (!(json->buf = av_malloc(json->buf_size)))
733         return AVERROR(ENOMEM);
734
735     return 0;
736 }
737
738 static av_cold void json_uninit(WriterContext *wctx)
739 {
740     JSONContext *json = wctx->priv;
741     av_freep(&json->buf);
742 }
743
744 static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
745                                    void *log_ctx)
746 {
747     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
748     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
749     const char *p;
750     char *q;
751     size_t size = 1;
752
753     // compute the length of the escaped string
754     for (p = src; *p; p++) {
755         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
756         if (strchr(json_escape, *p))     size += 2; // simple escape
757         else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
758         else                             size += 1; // char copy
759     }
760     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
761
762     q = *dst;
763     for (p = src; *p; p++) {
764         char *s = strchr(json_escape, *p);
765         if (s) {
766             *q++ = '\\';
767             *q++ = json_subst[s - json_escape];
768         } else if ((unsigned char)*p < 32) {
769             snprintf(q, 7, "\\u00%02x", *p & 0xff);
770             q += 6;
771         } else {
772             *q++ = *p;
773         }
774     }
775     *q = 0;
776     return *dst;
777 }
778
779 static void json_print_header(WriterContext *wctx)
780 {
781     JSONContext *json = wctx->priv;
782     printf("{");
783     json->indent_level++;
784 }
785
786 static void json_print_footer(WriterContext *wctx)
787 {
788     JSONContext *json = wctx->priv;
789     json->indent_level--;
790     printf("\n}\n");
791 }
792
793 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
794
795 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
796 {
797     JSONContext *json = wctx->priv;
798
799     if (wctx->nb_chapter)
800         printf(",");
801     printf("\n");
802     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
803                              !strcmp(chapter, "packets_and_frames") ||
804                              !strcmp(chapter, "streams");
805     if (json->multiple_entries) {
806         JSON_INDENT();
807         printf("\"%s\": [\n", json_escape_str(&json->buf, &json->buf_size, chapter, wctx));
808         json->print_packets_and_frames = !strcmp(chapter, "packets_and_frames");
809         json->indent_level++;
810     }
811 }
812
813 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
814 {
815     JSONContext *json = wctx->priv;
816
817     if (json->multiple_entries) {
818         printf("\n");
819         json->indent_level--;
820         JSON_INDENT();
821         printf("]");
822     }
823 }
824
825 static void json_print_section_header(WriterContext *wctx, const char *section)
826 {
827     JSONContext *json = wctx->priv;
828
829     if (wctx->nb_section)
830         printf(",\n");
831     JSON_INDENT();
832     if (!json->multiple_entries)
833         printf("\"%s\": ", section);
834     printf("{\n");
835     json->indent_level++;
836     /* this is required so the parser can distinguish between packets and frames */
837     if (json->print_packets_and_frames) {
838         JSON_INDENT(); printf("\"type\": \"%s\",\n", section);
839     }
840 }
841
842 static void json_print_section_footer(WriterContext *wctx, const char *section)
843 {
844     JSONContext *json = wctx->priv;
845
846     printf("\n");
847     json->indent_level--;
848     JSON_INDENT(); printf("}");
849 }
850
851 static inline void json_print_item_str(WriterContext *wctx,
852                                        const char *key, const char *value)
853 {
854     JSONContext *json = wctx->priv;
855
856     JSON_INDENT();
857     printf("\"%s\":", json_escape_str(&json->buf, &json->buf_size, key,   wctx));
858     printf(" \"%s\"", json_escape_str(&json->buf, &json->buf_size, value, wctx));
859 }
860
861 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
862 {
863     if (wctx->nb_item) printf(",\n");
864     json_print_item_str(wctx, key, value);
865 }
866
867 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
868 {
869     JSONContext *json = wctx->priv;
870
871     if (wctx->nb_item) printf(",\n");
872     JSON_INDENT();
873     printf("\"%s\": %lld",
874            json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
875 }
876
877 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
878 {
879     JSONContext *json = wctx->priv;
880     AVDictionaryEntry *tag = NULL;
881     int is_first = 1;
882     if (!dict)
883         return;
884     printf(",\n"); JSON_INDENT(); printf("\"tags\": {\n");
885     json->indent_level++;
886     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
887         if (is_first) is_first = 0;
888         else          printf(",\n");
889         json_print_item_str(wctx, tag->key, tag->value);
890     }
891     json->indent_level--;
892     printf("\n"); JSON_INDENT(); printf("}");
893 }
894
895 static const Writer json_writer = {
896     .name                 = "json",
897     .priv_size            = sizeof(JSONContext),
898     .init                 = json_init,
899     .uninit               = json_uninit,
900     .print_header         = json_print_header,
901     .print_footer         = json_print_footer,
902     .print_chapter_header = json_print_chapter_header,
903     .print_chapter_footer = json_print_chapter_footer,
904     .print_section_header = json_print_section_header,
905     .print_section_footer = json_print_section_footer,
906     .print_integer        = json_print_int,
907     .print_string         = json_print_str,
908     .show_tags            = json_show_tags,
909     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
910 };
911
912 /* XML output */
913
914 typedef struct {
915     const AVClass *class;
916     int within_tag;
917     int multiple_entries; ///< tells if the given chapter requires multiple entries
918     int indent_level;
919     int fully_qualified;
920     int xsd_strict;
921     char *buf;
922     size_t buf_size;
923 } XMLContext;
924
925 #undef OFFSET
926 #define OFFSET(x) offsetof(XMLContext, x)
927
928 static const AVOption xml_options[] = {
929     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
930     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
931     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
932     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
933     {NULL},
934 };
935
936 static const char *xml_get_name(void *ctx)
937 {
938     return "xml";
939 }
940
941 static const AVClass xml_class = {
942     "XMLContext",
943     xml_get_name,
944     xml_options
945 };
946
947 static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
948 {
949     XMLContext *xml = wctx->priv;
950     int err;
951
952     xml->class = &xml_class;
953     av_opt_set_defaults(xml);
954
955     if (args &&
956         (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
957         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
958         return err;
959     }
960
961     if (xml->xsd_strict) {
962         xml->fully_qualified = 1;
963 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
964         if (opt) {                                                      \
965             av_log(wctx, AV_LOG_ERROR,                                  \
966                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
967                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
968             return AVERROR(EINVAL);                                     \
969         }
970         CHECK_COMPLIANCE(show_private_data, "private");
971         CHECK_COMPLIANCE(show_value_unit,   "unit");
972         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
973
974         if (do_show_frames && do_show_packets) {
975             av_log(wctx, AV_LOG_ERROR,
976                    "Interleaved frames and packets are not allowed in XSD. "
977                    "Select only one between the -show_frames and the -show_packets options.\n");
978             return AVERROR(EINVAL);
979         }
980     }
981
982     xml->buf_size = ESCAPE_INIT_BUF_SIZE;
983     if (!(xml->buf = av_malloc(xml->buf_size)))
984         return AVERROR(ENOMEM);
985     return 0;
986 }
987
988 static av_cold void xml_uninit(WriterContext *wctx)
989 {
990     XMLContext *xml = wctx->priv;
991     av_freep(&xml->buf);
992 }
993
994 static const char *xml_escape_str(char **dst, size_t *dst_size, const char *src,
995                                   void *log_ctx)
996 {
997     const char *p;
998     char *q;
999     size_t size = 1;
1000
1001     /* precompute size */
1002     for (p = src; *p; p++, size++) {
1003         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-10);
1004         switch (*p) {
1005         case '&' : size += strlen("&amp;");  break;
1006         case '<' : size += strlen("&lt;");   break;
1007         case '>' : size += strlen("&gt;");   break;
1008         case '\"': size += strlen("&quot;"); break;
1009         case '\'': size += strlen("&apos;"); break;
1010         default: size++;
1011         }
1012     }
1013     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
1014
1015 #define COPY_STR(str) {      \
1016         const char *s = str; \
1017         while (*s)           \
1018             *q++ = *s++;     \
1019     }
1020
1021     p = src;
1022     q = *dst;
1023     while (*p) {
1024         switch (*p) {
1025         case '&' : COPY_STR("&amp;");  break;
1026         case '<' : COPY_STR("&lt;");   break;
1027         case '>' : COPY_STR("&gt;");   break;
1028         case '\"': COPY_STR("&quot;"); break;
1029         case '\'': COPY_STR("&apos;"); break;
1030         default: *q++ = *p;
1031         }
1032         p++;
1033     }
1034     *q = 0;
1035
1036     return *dst;
1037 }
1038
1039 static void xml_print_header(WriterContext *wctx)
1040 {
1041     XMLContext *xml = wctx->priv;
1042     const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1043         "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1044         "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1045
1046     printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1047     printf("<%sffprobe%s>\n",
1048            xml->fully_qualified ? "ffprobe:" : "",
1049            xml->fully_qualified ? qual : "");
1050
1051     xml->indent_level++;
1052 }
1053
1054 static void xml_print_footer(WriterContext *wctx)
1055 {
1056     XMLContext *xml = wctx->priv;
1057
1058     xml->indent_level--;
1059     printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1060 }
1061
1062 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1063
1064 static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
1065 {
1066     XMLContext *xml = wctx->priv;
1067
1068     if (wctx->nb_chapter)
1069         printf("\n");
1070     xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames") ||
1071                             !strcmp(chapter, "packets_and_frames") ||
1072                             !strcmp(chapter, "streams");
1073
1074     if (xml->multiple_entries) {
1075         XML_INDENT(); printf("<%s>\n", chapter);
1076         xml->indent_level++;
1077     }
1078 }
1079
1080 static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
1081 {
1082     XMLContext *xml = wctx->priv;
1083
1084     if (xml->multiple_entries) {
1085         xml->indent_level--;
1086         XML_INDENT(); printf("</%s>\n", chapter);
1087     }
1088 }
1089
1090 static void xml_print_section_header(WriterContext *wctx, const char *section)
1091 {
1092     XMLContext *xml = wctx->priv;
1093
1094     XML_INDENT(); printf("<%s ", section);
1095     xml->within_tag = 1;
1096 }
1097
1098 static void xml_print_section_footer(WriterContext *wctx, const char *section)
1099 {
1100     XMLContext *xml = wctx->priv;
1101
1102     if (xml->within_tag)
1103         printf("/>\n");
1104     else {
1105         XML_INDENT(); printf("</%s>\n", section);
1106     }
1107 }
1108
1109 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1110 {
1111     XMLContext *xml = wctx->priv;
1112
1113     if (wctx->nb_item)
1114         printf(" ");
1115     printf("%s=\"%s\"", key, xml_escape_str(&xml->buf, &xml->buf_size, value, wctx));
1116 }
1117
1118 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1119 {
1120     if (wctx->nb_item)
1121         printf(" ");
1122     printf("%s=\"%lld\"", key, value);
1123 }
1124
1125 static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
1126 {
1127     XMLContext *xml = wctx->priv;
1128     AVDictionaryEntry *tag = NULL;
1129     int is_first = 1;
1130
1131     xml->indent_level++;
1132     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1133         if (is_first) {
1134             /* close section tag */
1135             printf(">\n");
1136             xml->within_tag = 0;
1137             is_first = 0;
1138         }
1139         XML_INDENT();
1140         printf("<tag key=\"%s\"",
1141                xml_escape_str(&xml->buf, &xml->buf_size, tag->key,   wctx));
1142         printf(" value=\"%s\"/>\n",
1143                xml_escape_str(&xml->buf, &xml->buf_size, tag->value, wctx));
1144     }
1145     xml->indent_level--;
1146 }
1147
1148 static Writer xml_writer = {
1149     .name                 = "xml",
1150     .priv_size            = sizeof(XMLContext),
1151     .init                 = xml_init,
1152     .uninit               = xml_uninit,
1153     .print_header         = xml_print_header,
1154     .print_footer         = xml_print_footer,
1155     .print_chapter_header = xml_print_chapter_header,
1156     .print_chapter_footer = xml_print_chapter_footer,
1157     .print_section_header = xml_print_section_header,
1158     .print_section_footer = xml_print_section_footer,
1159     .print_integer        = xml_print_int,
1160     .print_string         = xml_print_str,
1161     .show_tags            = xml_show_tags,
1162     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1163 };
1164
1165 static void writer_register_all(void)
1166 {
1167     static int initialized;
1168
1169     if (initialized)
1170         return;
1171     initialized = 1;
1172
1173     writer_register(&default_writer);
1174     writer_register(&compact_writer);
1175     writer_register(&csv_writer);
1176     writer_register(&json_writer);
1177     writer_register(&xml_writer);
1178 }
1179
1180 #define print_fmt(k, f, ...) do {              \
1181     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
1182         writer_print_string(w, k, pbuf.s, 0);  \
1183 } while (0)
1184
1185 #define print_fmt_opt(k, f, ...) do {          \
1186     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
1187         writer_print_string(w, k, pbuf.s, 1);  \
1188 } while (0)
1189
1190 #define print_int(k, v)         writer_print_integer(w, k, v)
1191 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1192 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1193 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
1194 #define print_ts(k, v)          writer_print_ts(w, k, v)
1195 #define print_val(k, v, u)      writer_print_string(w, k, \
1196     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
1197 #define print_section_header(s) writer_print_section_header(w, s)
1198 #define print_section_footer(s) writer_print_section_footer(w, s)
1199 #define show_tags(metadata)     writer_show_tags(w, metadata)
1200
1201 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1202 {
1203     char val_str[128];
1204     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1205     struct print_buf pbuf = {.s = NULL};
1206     const char *s;
1207
1208     print_section_header("packet");
1209     s = av_get_media_type_string(st->codec->codec_type);
1210     if (s) print_str    ("codec_type", s);
1211     else   print_str_opt("codec_type", "unknown");
1212     print_int("stream_index",     pkt->stream_index);
1213     print_ts  ("pts",             pkt->pts);
1214     print_time("pts_time",        pkt->pts, &st->time_base);
1215     print_ts  ("dts",             pkt->dts);
1216     print_time("dts_time",        pkt->dts, &st->time_base);
1217     print_ts  ("duration",        pkt->duration);
1218     print_time("duration_time",   pkt->duration, &st->time_base);
1219     print_val("size",             pkt->size, unit_byte_str);
1220     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1221     else                print_str_opt("pos", "N/A");
1222     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1223     print_section_footer("packet");
1224
1225     av_free(pbuf.s);
1226     fflush(stdout);
1227 }
1228
1229 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
1230 {
1231     struct print_buf pbuf = {.s = NULL};
1232     const char *s;
1233
1234     print_section_header("frame");
1235     print_str("media_type",             "video");
1236     print_int("width",                  frame->width);
1237     print_int("height",                 frame->height);
1238     s = av_get_pix_fmt_name(frame->format);
1239     if (s) print_str    ("pix_fmt", s);
1240     else   print_str_opt("pix_fmt", "unknown");
1241     if (frame->sample_aspect_ratio.num) {
1242         print_fmt("sample_aspect_ratio", "%d:%d",
1243                   frame->sample_aspect_ratio.num,
1244                   frame->sample_aspect_ratio.den);
1245     } else {
1246         print_str_opt("sample_aspect_ratio", "N/A");
1247     }
1248     print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1249     print_int("coded_picture_number",   frame->coded_picture_number);
1250     print_int("display_picture_number", frame->display_picture_number);
1251     print_int("interlaced_frame",       frame->interlaced_frame);
1252     print_int("top_field_first",        frame->top_field_first);
1253     print_int("repeat_pict",            frame->repeat_pict);
1254     print_int("reference",              frame->reference);
1255     print_int("key_frame",              frame->key_frame);
1256     print_ts  ("pkt_pts",               frame->pkt_pts);
1257     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1258     print_ts  ("pkt_dts",               frame->pkt_dts);
1259     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1260     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1261     else                      print_str_opt("pkt_pos", "N/A");
1262     print_section_footer("frame");
1263
1264     av_free(pbuf.s);
1265     fflush(stdout);
1266 }
1267
1268 static av_always_inline int get_video_frame(AVFormatContext *fmt_ctx,
1269                                             AVFrame *frame, AVPacket *pkt)
1270 {
1271     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1272     int got_picture = 0;
1273
1274     if (dec_ctx->codec_id   != CODEC_ID_NONE &&
1275         dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
1276         avcodec_decode_video2(dec_ctx, frame, &got_picture, pkt);
1277     return got_picture;
1278 }
1279
1280 static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1281 {
1282     AVPacket pkt;
1283     AVFrame frame;
1284     int i = 0;
1285
1286     av_init_packet(&pkt);
1287
1288     while (!av_read_frame(fmt_ctx, &pkt)) {
1289         if (do_show_packets)
1290             show_packet(w, fmt_ctx, &pkt, i++);
1291         if (do_show_frames &&
1292             get_video_frame(fmt_ctx, &frame, &pkt)) {
1293             show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1294             av_destruct_packet(&pkt);
1295         }
1296     }
1297     av_init_packet(&pkt);
1298     pkt.data = NULL;
1299     pkt.size = 0;
1300     //Flush remaining frames that are cached in the decoder
1301     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1302         pkt.stream_index = i;
1303         while (get_video_frame(fmt_ctx, &frame, &pkt))
1304             show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1305     }
1306 }
1307
1308 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1309 {
1310     AVStream *stream = fmt_ctx->streams[stream_idx];
1311     AVCodecContext *dec_ctx;
1312     AVCodec *dec;
1313     char val_str[128];
1314     const char *s;
1315     AVRational display_aspect_ratio;
1316     struct print_buf pbuf = {.s = NULL};
1317
1318     print_section_header("stream");
1319
1320     print_int("index", stream->index);
1321
1322     if ((dec_ctx = stream->codec)) {
1323         if ((dec = dec_ctx->codec)) {
1324             print_str("codec_name",      dec->name);
1325             print_str("codec_long_name", dec->long_name);
1326         } else {
1327             print_str_opt("codec_name",      "unknown");
1328             print_str_opt("codec_long_name", "unknown");
1329         }
1330
1331         s = av_get_media_type_string(dec_ctx->codec_type);
1332         if (s) print_str    ("codec_type", s);
1333         else   print_str_opt("codec_type", "unknown");
1334         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
1335
1336         /* print AVI/FourCC tag */
1337         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1338         print_str("codec_tag_string",    val_str);
1339         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1340
1341         switch (dec_ctx->codec_type) {
1342         case AVMEDIA_TYPE_VIDEO:
1343             print_int("width",        dec_ctx->width);
1344             print_int("height",       dec_ctx->height);
1345             print_int("has_b_frames", dec_ctx->has_b_frames);
1346             if (dec_ctx->sample_aspect_ratio.num) {
1347                 print_fmt("sample_aspect_ratio", "%d:%d",
1348                           dec_ctx->sample_aspect_ratio.num,
1349                           dec_ctx->sample_aspect_ratio.den);
1350                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1351                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
1352                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
1353                           1024*1024);
1354                 print_fmt("display_aspect_ratio", "%d:%d",
1355                           display_aspect_ratio.num,
1356                           display_aspect_ratio.den);
1357             } else {
1358                 print_str_opt("sample_aspect_ratio", "N/A");
1359                 print_str_opt("display_aspect_ratio", "N/A");
1360             }
1361             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1362             if (s) print_str    ("pix_fmt", s);
1363             else   print_str_opt("pix_fmt", "unknown");
1364             print_int("level",   dec_ctx->level);
1365             if (dec_ctx->timecode_frame_start >= 0) {
1366                 uint32_t tc = dec_ctx->timecode_frame_start;
1367                 print_fmt("timecode", "%02d:%02d:%02d%c%02d",
1368                           tc>>19 & 0x1f,              // hours
1369                           tc>>13 & 0x3f,              // minutes
1370                           tc>>6  & 0x3f,              // seconds
1371                           tc     & 1<<24 ? ';' : ':', // drop
1372                           tc     & 0x3f);             // frames
1373             } else {
1374                 print_str_opt("timecode", "N/A");
1375             }
1376             break;
1377
1378         case AVMEDIA_TYPE_AUDIO:
1379             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1380             if (s) print_str    ("sample_fmt", s);
1381             else   print_str_opt("sample_fmt", "unknown");
1382             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1383             print_int("channels",        dec_ctx->channels);
1384             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1385             break;
1386         }
1387     } else {
1388         print_str_opt("codec_type", "unknown");
1389     }
1390     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1391         const AVOption *opt = NULL;
1392         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1393             uint8_t *str;
1394             if (opt->flags) continue;
1395             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1396                 print_str(opt->name, str);
1397                 av_free(str);
1398             }
1399         }
1400     }
1401
1402     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1403     else                                          print_str_opt("id", "N/A");
1404     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1405     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1406     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1407     print_time("start_time",    stream->start_time, &stream->time_base);
1408     print_time("duration",      stream->duration,   &stream->time_base);
1409     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1410     else                   print_str_opt("nb_frames", "N/A");
1411     show_tags(stream->metadata);
1412
1413     print_section_footer("stream");
1414     av_free(pbuf.s);
1415     fflush(stdout);
1416 }
1417
1418 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1419 {
1420     int i;
1421     for (i = 0; i < fmt_ctx->nb_streams; i++)
1422         show_stream(w, fmt_ctx, i);
1423 }
1424
1425 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1426 {
1427     char val_str[128];
1428     int64_t size = avio_size(fmt_ctx->pb);
1429
1430     print_section_header("format");
1431     print_str("filename",         fmt_ctx->filename);
1432     print_int("nb_streams",       fmt_ctx->nb_streams);
1433     print_str("format_name",      fmt_ctx->iformat->name);
1434     print_str("format_long_name", fmt_ctx->iformat->long_name);
1435     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1436     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1437     if (size >= 0) print_val    ("size", size, unit_byte_str);
1438     else           print_str_opt("size", "N/A");
1439     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1440     else                       print_str_opt("bit_rate", "N/A");
1441     show_tags(fmt_ctx->metadata);
1442     print_section_footer("format");
1443     fflush(stdout);
1444 }
1445
1446 static void show_error(WriterContext *w, int err)
1447 {
1448     char errbuf[128];
1449     const char *errbuf_ptr = errbuf;
1450
1451     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1452         errbuf_ptr = strerror(AVUNERROR(err));
1453
1454     writer_print_chapter_header(w, "error");
1455     print_section_header("error");
1456     print_int("code", err);
1457     print_str("string", errbuf_ptr);
1458     print_section_footer("error");
1459     writer_print_chapter_footer(w, "error");
1460 }
1461
1462 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1463 {
1464     int err, i;
1465     AVFormatContext *fmt_ctx = NULL;
1466     AVDictionaryEntry *t;
1467
1468     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
1469         print_error(filename, err);
1470         return err;
1471     }
1472     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1473         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1474         return AVERROR_OPTION_NOT_FOUND;
1475     }
1476
1477
1478     /* fill the streams in the format context */
1479     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1480         print_error(filename, err);
1481         return err;
1482     }
1483
1484     av_dump_format(fmt_ctx, 0, filename, 0);
1485
1486     /* bind a decoder to each input stream */
1487     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1488         AVStream *stream = fmt_ctx->streams[i];
1489         AVCodec *codec;
1490
1491         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1492             av_log(NULL, AV_LOG_ERROR, "Unsupported codec with id %d for input stream %d\n",
1493                    stream->codec->codec_id, stream->index);
1494         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1495             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1496                    stream->index);
1497         }
1498     }
1499
1500     *fmt_ctx_ptr = fmt_ctx;
1501     return 0;
1502 }
1503
1504 #define PRINT_CHAPTER(name) do {                                        \
1505     if (do_show_ ## name) {                                             \
1506         writer_print_chapter_header(wctx, #name);                       \
1507         show_ ## name (wctx, fmt_ctx);                                  \
1508         writer_print_chapter_footer(wctx, #name);                       \
1509     }                                                                   \
1510 } while (0)
1511
1512 static int probe_file(WriterContext *wctx, const char *filename)
1513 {
1514     AVFormatContext *fmt_ctx;
1515     int ret, i;
1516
1517     ret = open_input_file(&fmt_ctx, filename);
1518     if (ret >= 0) {
1519         if (do_show_packets || do_show_frames) {
1520             const char *chapter;
1521             if (do_show_frames && do_show_packets &&
1522                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1523                 chapter = "packets_and_frames";
1524             else if (do_show_packets && !do_show_frames)
1525                 chapter = "packets";
1526             else // (!do_show_packets && do_show_frames)
1527                 chapter = "frames";
1528             writer_print_chapter_header(wctx, chapter);
1529             show_packets(wctx, fmt_ctx);
1530             writer_print_chapter_footer(wctx, chapter);
1531         }
1532         PRINT_CHAPTER(streams);
1533         PRINT_CHAPTER(format);
1534         for (i = 0; i < fmt_ctx->nb_streams; i++)
1535             if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
1536                 avcodec_close(fmt_ctx->streams[i]->codec);
1537         avformat_close_input(&fmt_ctx);
1538     }
1539
1540     return ret;
1541 }
1542
1543 static void show_usage(void)
1544 {
1545     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1546     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1547     av_log(NULL, AV_LOG_INFO, "\n");
1548 }
1549
1550 static int opt_format(const char *opt, const char *arg)
1551 {
1552     iformat = av_find_input_format(arg);
1553     if (!iformat) {
1554         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1555         return AVERROR(EINVAL);
1556     }
1557     return 0;
1558 }
1559
1560 static void opt_input_file(void *optctx, const char *arg)
1561 {
1562     if (input_filename) {
1563         av_log(NULL, AV_LOG_ERROR, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1564                arg, input_filename);
1565         exit(1);
1566     }
1567     if (!strcmp(arg, "-"))
1568         arg = "pipe:";
1569     input_filename = arg;
1570 }
1571
1572 static int opt_help(const char *opt, const char *arg)
1573 {
1574     av_log_set_callback(log_callback_help);
1575     show_usage();
1576     show_help_options(options, "Main options:\n", 0, 0);
1577     printf("\n");
1578
1579     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1580
1581     return 0;
1582 }
1583
1584 static int opt_pretty(const char *opt, const char *arg)
1585 {
1586     show_value_unit              = 1;
1587     use_value_prefix             = 1;
1588     use_byte_value_binary_prefix = 1;
1589     use_value_sexagesimal_format = 1;
1590     return 0;
1591 }
1592
1593 static const OptionDef options[] = {
1594 #include "cmdutils_common_opts.h"
1595     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1596     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1597     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1598     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1599       "use binary prefixes for byte units" },
1600     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1601       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1602     { "pretty", 0, {(void*)&opt_pretty},
1603       "prettify the format of displayed values, make it more human readable" },
1604     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1605       "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
1606     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
1607     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1608     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
1609     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1610     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1611     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
1612     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
1613     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1614     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1615     { NULL, },
1616 };
1617
1618 int main(int argc, char **argv)
1619 {
1620     const Writer *w;
1621     WriterContext *wctx;
1622     char *buf;
1623     char *w_name = NULL, *w_args = NULL;
1624     int ret;
1625
1626     parse_loglevel(argc, argv, options);
1627     av_register_all();
1628     avformat_network_init();
1629     init_opts();
1630 #if CONFIG_AVDEVICE
1631     avdevice_register_all();
1632 #endif
1633
1634     show_banner(argc, argv, options);
1635     parse_options(NULL, argc, argv, options, opt_input_file);
1636
1637     writer_register_all();
1638
1639     if (!print_format)
1640         print_format = av_strdup("default");
1641     w_name = av_strtok(print_format, "=", &buf);
1642     w_args = buf;
1643
1644     w = writer_get_by_name(w_name);
1645     if (!w) {
1646         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1647         ret = AVERROR(EINVAL);
1648         goto end;
1649     }
1650
1651     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
1652         writer_print_header(wctx);
1653
1654         if (!input_filename) {
1655             show_usage();
1656             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
1657             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1658             ret = AVERROR(EINVAL);
1659         } else {
1660             ret = probe_file(wctx, input_filename);
1661             if (ret < 0 && do_show_error)
1662                 show_error(wctx, ret);
1663         }
1664
1665         writer_print_footer(wctx);
1666         writer_close(&wctx);
1667     }
1668
1669 end:
1670     av_freep(&print_format);
1671     avformat_network_deinit();
1672
1673     return ret;
1674 }