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