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