]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
ffprobe: Rename variable in csv_escape_str()
[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 #include "version.h"
28
29 #include <string.h>
30
31 #include "libavformat/avformat.h"
32 #include "libavcodec/avcodec.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/bprint.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/libm.h"
39 #include "libavutil/timecode.h"
40 #include "libavdevice/avdevice.h"
41 #include "libswscale/swscale.h"
42 #include "libswresample/swresample.h"
43 #include "libpostproc/postprocess.h"
44 #include "cmdutils.h"
45
46 const char program_name[] = "ffprobe";
47 const int program_birth_year = 2007;
48
49 static int do_bitexact = 0;
50 static int do_count_frames = 0;
51 static int do_count_packets = 0;
52 static int do_read_frames  = 0;
53 static int do_read_packets = 0;
54 static int do_show_error   = 0;
55 static int do_show_format  = 0;
56 static int do_show_frames  = 0;
57 static AVDictionary *fmt_entries_to_show = NULL;
58 static int do_show_packets = 0;
59 static int do_show_streams = 0;
60 static int do_show_data    = 0;
61 static int do_show_program_version  = 0;
62 static int do_show_library_versions = 0;
63
64 static int show_value_unit              = 0;
65 static int use_value_prefix             = 0;
66 static int use_byte_value_binary_prefix = 0;
67 static int use_value_sexagesimal_format = 0;
68 static int show_private_data            = 1;
69
70 static char *print_format;
71
72 static const OptionDef *options;
73
74 /* FFprobe context */
75 static const char *input_filename;
76 static AVInputFormat *iformat = NULL;
77
78 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
79 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
80
81 static const char unit_second_str[]         = "s"    ;
82 static const char unit_hertz_str[]          = "Hz"   ;
83 static const char unit_byte_str[]           = "byte" ;
84 static const char unit_bit_per_second_str[] = "bit/s";
85 static uint64_t *nb_streams_packets;
86 static uint64_t *nb_streams_frames;
87
88 void av_noreturn exit_program(int ret)
89 {
90     av_dict_free(&fmt_entries_to_show);
91     exit(ret);
92 }
93
94 struct unit_value {
95     union { double d; long long int i; } val;
96     const char *unit;
97 };
98
99 static char *value_string(char *buf, int buf_size, struct unit_value uv)
100 {
101     double vald;
102     long long int vali;
103     int show_float = 0;
104
105     if (uv.unit == unit_second_str) {
106         vald = uv.val.d;
107         show_float = 1;
108     } else {
109         vald = vali = uv.val.i;
110     }
111
112     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
113         double secs;
114         int hours, mins;
115         secs  = vald;
116         mins  = (int)secs / 60;
117         secs  = secs - mins * 60;
118         hours = mins / 60;
119         mins %= 60;
120         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
121     } else {
122         const char *prefix_string = "";
123
124         if (use_value_prefix && vald > 1) {
125             long long int index;
126
127             if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
128                 index = (long long int) (log2(vald)) / 10;
129                 index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
130                 vald /= exp2(index * 10);
131                 prefix_string = binary_unit_prefixes[index];
132             } else {
133                 index = (long long int) (log10(vald)) / 3;
134                 index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
135                 vald /= pow(10, index * 3);
136                 prefix_string = decimal_unit_prefixes[index];
137             }
138         }
139
140         if (show_float || (use_value_prefix && vald != (long long int)vald))
141             snprintf(buf, buf_size, "%f", vald);
142         else
143             snprintf(buf, buf_size, "%lld", vali);
144         av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
145                  prefix_string, show_value_unit ? uv.unit : "");
146     }
147
148     return buf;
149 }
150
151 /* WRITERS API */
152
153 typedef struct WriterContext WriterContext;
154
155 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
156 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
157
158 typedef struct Writer {
159     const AVClass *priv_class;      ///< private class of the writer, if any
160     int priv_size;                  ///< private size for the writer context
161     const char *name;
162
163     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
164     void (*uninit)(WriterContext *wctx);
165
166     void (*print_header)(WriterContext *ctx);
167     void (*print_footer)(WriterContext *ctx);
168
169     void (*print_chapter_header)(WriterContext *wctx, const char *);
170     void (*print_chapter_footer)(WriterContext *wctx, const char *);
171     void (*print_section_header)(WriterContext *wctx, const char *);
172     void (*print_section_footer)(WriterContext *wctx, const char *);
173     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
174     void (*print_rational)      (WriterContext *wctx, AVRational *q, char *sep);
175     void (*print_string)        (WriterContext *wctx, const char *, const char *);
176     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
177     int flags;                  ///< a combination or WRITER_FLAG_*
178 } Writer;
179
180 struct WriterContext {
181     const AVClass *class;           ///< class of the writer
182     const Writer *writer;           ///< the Writer of which this is an instance
183     char *name;                     ///< name of this writer instance
184     void *priv;                     ///< private data for use by the filter
185     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
186     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
187     unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
188     unsigned int nb_section_frame;  ///< number of the frame  section in case we are in "packets_and_frames" section
189     unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
190     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
191
192     int multiple_sections;          ///< tells if the current chapter can contain multiple sections
193     int is_fmt_chapter;             ///< tells if the current chapter is "format", required by the print_format_entry option
194     int is_packets_and_frames;      ///< tells if the current section is "packets_and_frames"
195 };
196
197 static const char *writer_get_name(void *p)
198 {
199     WriterContext *wctx = p;
200     return wctx->writer->name;
201 }
202
203 static const AVClass writer_class = {
204     "Writer",
205     writer_get_name,
206     NULL,
207     LIBAVUTIL_VERSION_INT,
208 };
209
210 static void writer_close(WriterContext **wctx)
211 {
212     if (!*wctx)
213         return;
214
215     if ((*wctx)->writer->uninit)
216         (*wctx)->writer->uninit(*wctx);
217     if ((*wctx)->writer->priv_class)
218         av_opt_free((*wctx)->priv);
219     av_freep(&((*wctx)->priv));
220     av_freep(wctx);
221 }
222
223 static int writer_open(WriterContext **wctx, const Writer *writer,
224                        const char *args, void *opaque)
225 {
226     int ret = 0;
227
228     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
229         ret = AVERROR(ENOMEM);
230         goto fail;
231     }
232
233     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
234         ret = AVERROR(ENOMEM);
235         goto fail;
236     }
237
238     (*wctx)->class = &writer_class;
239     (*wctx)->writer = writer;
240
241     if (writer->priv_class) {
242         void *priv_ctx = (*wctx)->priv;
243         *((const AVClass **)priv_ctx) = writer->priv_class;
244         av_opt_set_defaults(priv_ctx);
245
246         if (args &&
247             (ret = av_set_options_string(priv_ctx, args, "=", ":")) < 0)
248             goto fail;
249     }
250     if ((*wctx)->writer->init)
251         ret = (*wctx)->writer->init(*wctx, args, opaque);
252     if (ret < 0)
253         goto fail;
254
255     return 0;
256
257 fail:
258     writer_close(wctx);
259     return ret;
260 }
261
262 static inline void writer_print_header(WriterContext *wctx)
263 {
264     if (wctx->writer->print_header)
265         wctx->writer->print_header(wctx);
266     wctx->nb_chapter = 0;
267 }
268
269 static inline void writer_print_footer(WriterContext *wctx)
270 {
271     if (wctx->writer->print_footer)
272         wctx->writer->print_footer(wctx);
273 }
274
275 static inline void writer_print_chapter_header(WriterContext *wctx,
276                                                const char *chapter)
277 {
278     wctx->nb_section =
279     wctx->nb_section_packet = wctx->nb_section_frame =
280     wctx->nb_section_packet_frame = 0;
281     wctx->is_packets_and_frames = !strcmp(chapter, "packets_and_frames");
282     wctx->multiple_sections = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
283                               wctx->is_packets_and_frames ||
284                               !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
285     wctx->is_fmt_chapter = !strcmp(chapter, "format");
286
287     if (wctx->writer->print_chapter_header)
288         wctx->writer->print_chapter_header(wctx, chapter);
289 }
290
291 static inline void writer_print_chapter_footer(WriterContext *wctx,
292                                                const char *chapter)
293 {
294     if (wctx->writer->print_chapter_footer)
295         wctx->writer->print_chapter_footer(wctx, chapter);
296     wctx->nb_chapter++;
297 }
298
299 static inline void writer_print_section_header(WriterContext *wctx,
300                                                const char *section)
301 {
302     if (wctx->is_packets_and_frames)
303         wctx->nb_section_packet_frame = !strcmp(section, "packet") ? wctx->nb_section_packet
304                                                                    : wctx->nb_section_frame;
305     if (wctx->writer->print_section_header)
306         wctx->writer->print_section_header(wctx, section);
307     wctx->nb_item = 0;
308 }
309
310 static inline void writer_print_section_footer(WriterContext *wctx,
311                                                const char *section)
312 {
313     if (wctx->writer->print_section_footer)
314         wctx->writer->print_section_footer(wctx, section);
315     if (wctx->is_packets_and_frames) {
316         if (!strcmp(section, "packet")) wctx->nb_section_packet++;
317         else                            wctx->nb_section_frame++;
318     }
319     wctx->nb_section++;
320 }
321
322 static inline void writer_print_integer(WriterContext *wctx,
323                                         const char *key, long long int val)
324 {
325     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
326         wctx->writer->print_integer(wctx, key, val);
327         wctx->nb_item++;
328     }
329 }
330
331 static inline void writer_print_rational(WriterContext *wctx,
332                                          const char *key, AVRational q, char sep)
333 {
334     AVBPrint buf;
335     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
336     av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
337     wctx->writer->print_string(wctx, key, buf.str);
338     wctx->nb_item++;
339 }
340
341 static inline void writer_print_string(WriterContext *wctx,
342                                        const char *key, const char *val, int opt)
343 {
344     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
345         return;
346     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
347         wctx->writer->print_string(wctx, key, val);
348         wctx->nb_item++;
349     }
350 }
351
352 static void writer_print_time(WriterContext *wctx, const char *key,
353                               int64_t ts, const AVRational *time_base, int is_duration)
354 {
355     char buf[128];
356
357     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
358         if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
359             writer_print_string(wctx, key, "N/A", 1);
360         } else {
361             double d = ts * av_q2d(*time_base);
362             struct unit_value uv;
363             uv.val.d = d;
364             uv.unit = unit_second_str;
365             value_string(buf, sizeof(buf), uv);
366             writer_print_string(wctx, key, buf, 0);
367         }
368     }
369 }
370
371 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
372 {
373     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
374         writer_print_string(wctx, key, "N/A", 1);
375     } else {
376         writer_print_integer(wctx, key, ts);
377     }
378 }
379
380 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
381 {
382     wctx->writer->show_tags(wctx, dict);
383 }
384
385 static void writer_print_data(WriterContext *wctx, const char *name,
386                               uint8_t *data, int size)
387 {
388     AVBPrint bp;
389     int offset = 0, l, i;
390
391     av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
392     av_bprintf(&bp, "\n");
393     while (size) {
394         av_bprintf(&bp, "%08x: ", offset);
395         l = FFMIN(size, 16);
396         for (i = 0; i < l; i++) {
397             av_bprintf(&bp, "%02x", data[i]);
398             if (i & 1)
399                 av_bprintf(&bp, " ");
400         }
401         av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
402         for (i = 0; i < l; i++)
403             av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
404         av_bprintf(&bp, "\n");
405         offset += l;
406         data   += l;
407         size   -= l;
408     }
409     writer_print_string(wctx, name, bp.str, 0);
410     av_bprint_finalize(&bp, NULL);
411 }
412
413 #define MAX_REGISTERED_WRITERS_NB 64
414
415 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
416
417 static int writer_register(const Writer *writer)
418 {
419     static int next_registered_writer_idx = 0;
420
421     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
422         return AVERROR(ENOMEM);
423
424     registered_writers[next_registered_writer_idx++] = writer;
425     return 0;
426 }
427
428 static const Writer *writer_get_by_name(const char *name)
429 {
430     int i;
431
432     for (i = 0; registered_writers[i]; i++)
433         if (!strcmp(registered_writers[i]->name, name))
434             return registered_writers[i];
435
436     return NULL;
437 }
438
439
440 /* WRITERS */
441
442 #define DEFINE_WRITER_CLASS(name)                   \
443 static const char *name##_get_name(void *ctx)       \
444 {                                                   \
445     return #name ;                                  \
446 }                                                   \
447 static const AVClass name##_class = {               \
448     #name,                                          \
449     name##_get_name,                                \
450     name##_options                                  \
451 }
452
453 /* Default output */
454
455 typedef struct DefaultContext {
456     const AVClass *class;
457     int nokey;
458     int noprint_wrappers;
459 } DefaultContext;
460
461 #define OFFSET(x) offsetof(DefaultContext, x)
462
463 static const AVOption default_options[] = {
464     { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
465     { "nw",               "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
466     { "nokey",          "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
467     { "nk",             "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
468     {NULL},
469 };
470
471 DEFINE_WRITER_CLASS(default);
472
473 /* lame uppercasing routine, assumes the string is lower case ASCII */
474 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
475 {
476     int i;
477     for (i = 0; src[i] && i < dst_size-1; i++)
478         dst[i] = av_toupper(src[i]);
479     dst[i] = 0;
480     return dst;
481 }
482
483 static void default_print_section_header(WriterContext *wctx, const char *section)
484 {
485     DefaultContext *def = wctx->priv;
486     char buf[32];
487
488     if (!def->noprint_wrappers)
489         printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
490 }
491
492 static void default_print_section_footer(WriterContext *wctx, const char *section)
493 {
494     DefaultContext *def = wctx->priv;
495     char buf[32];
496
497     if (!def->noprint_wrappers)
498         printf("[/%s]\n", upcase_string(buf, sizeof(buf), section));
499 }
500
501 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
502 {
503     DefaultContext *def = wctx->priv;
504     if (!def->nokey)
505         printf("%s=", key);
506     printf("%s\n", value);
507 }
508
509 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
510 {
511     DefaultContext *def = wctx->priv;
512
513     if (!def->nokey)
514         printf("%s=", key);
515     printf("%lld\n", value);
516 }
517
518 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
519 {
520     AVDictionaryEntry *tag = NULL;
521     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
522         if (!fmt_entries_to_show || (tag->key && av_dict_get(fmt_entries_to_show, tag->key, NULL, 0)))
523             printf("TAG:");
524         writer_print_string(wctx, tag->key, tag->value, 0);
525     }
526 }
527
528 static const Writer default_writer = {
529     .name                  = "default",
530     .priv_size             = sizeof(DefaultContext),
531     .print_section_header  = default_print_section_header,
532     .print_section_footer  = default_print_section_footer,
533     .print_integer         = default_print_int,
534     .print_string          = default_print_str,
535     .show_tags             = default_show_tags,
536     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
537     .priv_class            = &default_class,
538 };
539
540 /* Compact output */
541
542 /**
543  * Apply C-language-like string escaping.
544  */
545 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
546 {
547     const char *p;
548
549     for (p = src; *p; p++) {
550         switch (*p) {
551         case '\b': av_bprintf(dst, "%s", "\\b");  break;
552         case '\f': av_bprintf(dst, "%s", "\\f");  break;
553         case '\n': av_bprintf(dst, "%s", "\\n");  break;
554         case '\r': av_bprintf(dst, "%s", "\\r");  break;
555         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
556         default:
557             if (*p == sep)
558                 av_bprint_chars(dst, '\\', 1);
559             av_bprint_chars(dst, *p, 1);
560         }
561     }
562     return dst->str;
563 }
564
565 /**
566  * Quote fields containing special characters, check RFC4180.
567  */
568 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
569 {
570     int needs_quoting = !!src[strcspn(src, "\",\n\r")];
571
572     if (needs_quoting)
573         av_bprint_chars(dst, '\"', 1);
574
575     for (; *src; src++) {
576         if (*src == '"')
577             av_bprint_chars(dst, '\"', 1);
578         av_bprint_chars(dst, *src, 1);
579     }
580     if (needs_quoting)
581         av_bprint_chars(dst, '\"', 1);
582     return dst->str;
583 }
584
585 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
586 {
587     return src;
588 }
589
590 typedef struct CompactContext {
591     const AVClass *class;
592     char *item_sep_str;
593     char item_sep;
594     int nokey;
595     int print_section;
596     char *escape_mode_str;
597     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
598 } CompactContext;
599
600 #undef OFFSET
601 #define OFFSET(x) offsetof(CompactContext, x)
602
603 static const AVOption compact_options[]= {
604     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
605     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
606     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
607     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
608     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
609     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
610     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
611     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
612     {NULL},
613 };
614
615 DEFINE_WRITER_CLASS(compact);
616
617 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
618 {
619     CompactContext *compact = wctx->priv;
620
621     if (strlen(compact->item_sep_str) != 1) {
622         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
623                compact->item_sep_str);
624         return AVERROR(EINVAL);
625     }
626     compact->item_sep = compact->item_sep_str[0];
627
628     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
629     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
630     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
631     else {
632         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
633         return AVERROR(EINVAL);
634     }
635
636     return 0;
637 }
638
639 static void compact_print_section_header(WriterContext *wctx, const char *section)
640 {
641     CompactContext *compact = wctx->priv;
642
643     if (compact->print_section)
644         printf("%s%c", section, compact->item_sep);
645 }
646
647 static void compact_print_section_footer(WriterContext *wctx, const char *section)
648 {
649     printf("\n");
650 }
651
652 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
653 {
654     CompactContext *compact = wctx->priv;
655     AVBPrint buf;
656
657     if (wctx->nb_item) printf("%c", compact->item_sep);
658     if (!compact->nokey)
659         printf("%s=", key);
660     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
661     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
662     av_bprint_finalize(&buf, NULL);
663 }
664
665 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
666 {
667     CompactContext *compact = wctx->priv;
668
669     if (wctx->nb_item) printf("%c", compact->item_sep);
670     if (!compact->nokey)
671         printf("%s=", key);
672     printf("%lld", value);
673 }
674
675 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
676 {
677     CompactContext *compact = wctx->priv;
678     AVDictionaryEntry *tag = NULL;
679     AVBPrint buf;
680
681     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
682     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
683         if (wctx->nb_item) printf("%c", compact->item_sep);
684         if (!compact->nokey) {
685             av_bprint_clear(&buf);
686             printf("tag:%s=", compact->escape_str(&buf, tag->key, compact->item_sep, wctx));
687         }
688         av_bprint_clear(&buf);
689         printf("%s", compact->escape_str(&buf, tag->value, compact->item_sep, wctx));
690     }
691     av_bprint_finalize(&buf, NULL);
692 }
693
694 static const Writer compact_writer = {
695     .name                 = "compact",
696     .priv_size            = sizeof(CompactContext),
697     .init                 = compact_init,
698     .print_section_header = compact_print_section_header,
699     .print_section_footer = compact_print_section_footer,
700     .print_integer        = compact_print_int,
701     .print_string         = compact_print_str,
702     .show_tags            = compact_show_tags,
703     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
704     .priv_class           = &compact_class,
705 };
706
707 /* CSV output */
708
709 #undef OFFSET
710 #define OFFSET(x) offsetof(CompactContext, x)
711
712 static const AVOption csv_options[] = {
713     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
714     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
715     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
716     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
717     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
718     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
719     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
720     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
721     {NULL},
722 };
723
724 DEFINE_WRITER_CLASS(csv);
725
726 static const Writer csv_writer = {
727     .name                 = "csv",
728     .priv_size            = sizeof(CompactContext),
729     .init                 = compact_init,
730     .print_section_header = compact_print_section_header,
731     .print_section_footer = compact_print_section_footer,
732     .print_integer        = compact_print_int,
733     .print_string         = compact_print_str,
734     .show_tags            = compact_show_tags,
735     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
736     .priv_class           = &csv_class,
737 };
738
739 /* Flat output */
740
741 typedef struct FlatContext {
742     const AVClass *class;
743     const char *section, *chapter;
744     const char *sep_str;
745     char sep;
746     int hierarchical;
747 } FlatContext;
748
749 #undef OFFSET
750 #define OFFSET(x) offsetof(FlatContext, x)
751
752 static const AVOption flat_options[]= {
753     {"sep_char", "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
754     {"s",        "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
755     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
756     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
757     {NULL},
758 };
759
760 DEFINE_WRITER_CLASS(flat);
761
762 static av_cold int flat_init(WriterContext *wctx, const char *args, void *opaque)
763 {
764     FlatContext *flat = wctx->priv;
765
766     if (strlen(flat->sep_str) != 1) {
767         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
768                flat->sep_str);
769         return AVERROR(EINVAL);
770     }
771     flat->sep = flat->sep_str[0];
772     return 0;
773 }
774
775 static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
776 {
777     const char *p;
778
779     for (p = src; *p; p++) {
780         if (!((*p >= '0' && *p <= '9') ||
781               (*p >= 'a' && *p <= 'z') ||
782               (*p >= 'A' && *p <= 'Z')))
783             av_bprint_chars(dst, '_', 1);
784         else
785             av_bprint_chars(dst, *p, 1);
786     }
787     return dst->str;
788 }
789
790 static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
791 {
792     const char *p;
793
794     for (p = src; *p; p++) {
795         switch (*p) {
796         case '\n': av_bprintf(dst, "%s", "\\n");  break;
797         case '\r': av_bprintf(dst, "%s", "\\r");  break;
798         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
799         case '"':  av_bprintf(dst, "%s", "\\\""); break;
800         case '`':  av_bprintf(dst, "%s", "\\`");  break;
801         case '$':  av_bprintf(dst, "%s", "\\$");  break;
802         default:   av_bprint_chars(dst, *p, 1);   break;
803         }
804     }
805     return dst->str;
806 }
807
808 static void flat_print_chapter_header(WriterContext *wctx, const char *chapter)
809 {
810     FlatContext *flat = wctx->priv;
811     flat->chapter = chapter;
812 }
813
814 static void flat_print_section_header(WriterContext *wctx, const char *section)
815 {
816     FlatContext *flat = wctx->priv;
817     flat->section = section;
818 }
819
820 static void flat_print_section(WriterContext *wctx)
821 {
822     FlatContext *flat = wctx->priv;
823     int n = wctx->is_packets_and_frames ? wctx->nb_section_packet_frame
824                                         : wctx->nb_section;
825
826     if (flat->hierarchical && wctx->multiple_sections)
827         printf("%s%c", flat->chapter, flat->sep);
828     printf("%s%c", flat->section, flat->sep);
829     if (wctx->multiple_sections)
830         printf("%d%c", n, flat->sep);
831 }
832
833 static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
834 {
835     flat_print_section(wctx);
836     printf("%s=%lld\n", key, value);
837 }
838
839 static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
840 {
841     FlatContext *flat = wctx->priv;
842     AVBPrint buf;
843
844     flat_print_section(wctx);
845     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
846     printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
847     av_bprint_clear(&buf);
848     printf("\"%s\"\n", flat_escape_value_str(&buf, value));
849     av_bprint_finalize(&buf, NULL);
850 }
851
852 static void flat_show_tags(WriterContext *wctx, AVDictionary *dict)
853 {
854     FlatContext *flat = wctx->priv;
855     AVBPrint buf;
856     AVDictionaryEntry *tag = NULL;
857
858     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
859     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
860         flat_print_section(wctx);
861         av_bprint_clear(&buf);
862         printf("tags%c%s=", flat->sep, flat_escape_key_str(&buf, tag->key, flat->sep));
863         av_bprint_clear(&buf);
864         printf("\"%s\"\n", flat_escape_value_str(&buf, tag->value));
865     }
866     av_bprint_finalize(&buf, NULL);
867 }
868
869 static const Writer flat_writer = {
870     .name                  = "flat",
871     .priv_size             = sizeof(FlatContext),
872     .init                  = flat_init,
873     .print_chapter_header  = flat_print_chapter_header,
874     .print_section_header  = flat_print_section_header,
875     .print_integer         = flat_print_int,
876     .print_string          = flat_print_str,
877     .show_tags             = flat_show_tags,
878     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
879     .priv_class            = &flat_class,
880 };
881
882 /* INI format output */
883
884 typedef struct {
885     const AVClass *class;
886     AVBPrint chapter_name, section_name;
887     int hierarchical;
888 } INIContext;
889
890 #undef OFFSET
891 #define OFFSET(x) offsetof(INIContext, x)
892
893 static const AVOption ini_options[] = {
894     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
895     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
896     {NULL},
897 };
898
899 DEFINE_WRITER_CLASS(ini);
900
901 static av_cold int ini_init(WriterContext *wctx, const char *args, void *opaque)
902 {
903     INIContext *ini = wctx->priv;
904
905     av_bprint_init(&ini->chapter_name, 1, AV_BPRINT_SIZE_UNLIMITED);
906     av_bprint_init(&ini->section_name, 1, AV_BPRINT_SIZE_UNLIMITED);
907
908     return 0;
909 }
910
911 static av_cold void ini_uninit(WriterContext *wctx)
912 {
913     INIContext *ini = wctx->priv;
914     av_bprint_finalize(&ini->chapter_name, NULL);
915     av_bprint_finalize(&ini->section_name, NULL);
916 }
917
918 static void ini_print_header(WriterContext *wctx)
919 {
920     printf("# ffprobe output\n\n");
921 }
922
923 static char *ini_escape_str(AVBPrint *dst, const char *src)
924 {
925     int i = 0;
926     char c = 0;
927
928     while (c = src[i++]) {
929         switch (c) {
930         case '\b': av_bprintf(dst, "%s", "\\b"); break;
931         case '\f': av_bprintf(dst, "%s", "\\f"); break;
932         case '\n': av_bprintf(dst, "%s", "\\n"); break;
933         case '\r': av_bprintf(dst, "%s", "\\r"); break;
934         case '\t': av_bprintf(dst, "%s", "\\t"); break;
935         case '\\':
936         case '#' :
937         case '=' :
938         case ':' : av_bprint_chars(dst, '\\', 1);
939         default:
940             if ((unsigned char)c < 32)
941                 av_bprintf(dst, "\\x00%02x", c & 0xff);
942             else
943                 av_bprint_chars(dst, c, 1);
944             break;
945         }
946     }
947     return dst->str;
948 }
949
950 static void ini_print_chapter_header(WriterContext *wctx, const char *chapter)
951 {
952     INIContext *ini = wctx->priv;
953
954     av_bprint_clear(&ini->chapter_name);
955     av_bprintf(&ini->chapter_name, "%s", chapter);
956
957     if (wctx->nb_chapter)
958         printf("\n");
959 }
960
961 static void ini_print_section_header(WriterContext *wctx, const char *section)
962 {
963     INIContext *ini = wctx->priv;
964     int n = wctx->is_packets_and_frames ? wctx->nb_section_packet_frame
965                                         : wctx->nb_section;
966     if (wctx->nb_section)
967         printf("\n");
968     av_bprint_clear(&ini->section_name);
969
970     if (ini->hierarchical && wctx->multiple_sections)
971         av_bprintf(&ini->section_name, "%s.", ini->chapter_name.str);
972     av_bprintf(&ini->section_name, "%s", section);
973
974     if (wctx->multiple_sections)
975         av_bprintf(&ini->section_name, ".%d", n);
976     printf("[%s]\n", ini->section_name.str);
977 }
978
979 static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
980 {
981     AVBPrint buf;
982
983     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
984     printf("%s=", ini_escape_str(&buf, key));
985     av_bprint_clear(&buf);
986     printf("%s\n", ini_escape_str(&buf, value));
987     av_bprint_finalize(&buf, NULL);
988 }
989
990 static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
991 {
992     printf("%s=%lld\n", key, value);
993 }
994
995 static void ini_show_tags(WriterContext *wctx, AVDictionary *dict)
996 {
997     INIContext *ini = wctx->priv;
998     AVDictionaryEntry *tag = NULL;
999     int is_first = 1;
1000
1001     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1002         if (is_first) {
1003             printf("\n[%s.tags]\n", ini->section_name.str);
1004             is_first = 0;
1005         }
1006         writer_print_string(wctx, tag->key, tag->value, 0);
1007     }
1008 }
1009
1010 static const Writer ini_writer = {
1011     .name                  = "ini",
1012     .priv_size             = sizeof(INIContext),
1013     .init                  = ini_init,
1014     .uninit                = ini_uninit,
1015     .print_header          = ini_print_header,
1016     .print_chapter_header  = ini_print_chapter_header,
1017     .print_section_header  = ini_print_section_header,
1018     .print_integer         = ini_print_int,
1019     .print_string          = ini_print_str,
1020     .show_tags             = ini_show_tags,
1021     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1022     .priv_class            = &ini_class,
1023 };
1024
1025 /* JSON output */
1026
1027 typedef struct {
1028     const AVClass *class;
1029     int indent_level;
1030     int compact;
1031     const char *item_sep, *item_start_end;
1032 } JSONContext;
1033
1034 #undef OFFSET
1035 #define OFFSET(x) offsetof(JSONContext, x)
1036
1037 static const AVOption json_options[]= {
1038     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1039     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1040     { NULL }
1041 };
1042
1043 DEFINE_WRITER_CLASS(json);
1044
1045 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
1046 {
1047     JSONContext *json = wctx->priv;
1048
1049     json->item_sep       = json->compact ? ", " : ",\n";
1050     json->item_start_end = json->compact ? " "  : "\n";
1051
1052     return 0;
1053 }
1054
1055 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1056 {
1057     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
1058     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
1059     const char *p;
1060
1061     for (p = src; *p; p++) {
1062         char *s = strchr(json_escape, *p);
1063         if (s) {
1064             av_bprint_chars(dst, '\\', 1);
1065             av_bprint_chars(dst, json_subst[s - json_escape], 1);
1066         } else if ((unsigned char)*p < 32) {
1067             av_bprintf(dst, "\\u00%02x", *p & 0xff);
1068         } else {
1069             av_bprint_chars(dst, *p, 1);
1070         }
1071     }
1072     return dst->str;
1073 }
1074
1075 static void json_print_header(WriterContext *wctx)
1076 {
1077     JSONContext *json = wctx->priv;
1078     printf("{");
1079     json->indent_level++;
1080 }
1081
1082 static void json_print_footer(WriterContext *wctx)
1083 {
1084     JSONContext *json = wctx->priv;
1085     json->indent_level--;
1086     printf("\n}\n");
1087 }
1088
1089 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
1090
1091 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
1092 {
1093     JSONContext *json = wctx->priv;
1094     AVBPrint buf;
1095
1096     if (wctx->nb_chapter)
1097         printf(",");
1098     printf("\n");
1099     if (wctx->multiple_sections) {
1100         JSON_INDENT();
1101         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1102         printf("\"%s\": [\n", json_escape_str(&buf, chapter, wctx));
1103         av_bprint_finalize(&buf, NULL);
1104         json->indent_level++;
1105     }
1106 }
1107
1108 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
1109 {
1110     JSONContext *json = wctx->priv;
1111
1112     if (wctx->multiple_sections) {
1113         printf("\n");
1114         json->indent_level--;
1115         JSON_INDENT();
1116         printf("]");
1117     }
1118 }
1119
1120 static void json_print_section_header(WriterContext *wctx, const char *section)
1121 {
1122     JSONContext *json = wctx->priv;
1123
1124     if (wctx->nb_section)
1125         printf(",\n");
1126     JSON_INDENT();
1127     if (!wctx->multiple_sections)
1128         printf("\"%s\": ", section);
1129     printf("{%s", json->item_start_end);
1130     json->indent_level++;
1131     /* this is required so the parser can distinguish between packets and frames */
1132     if (wctx->is_packets_and_frames) {
1133         if (!json->compact)
1134             JSON_INDENT();
1135         printf("\"type\": \"%s\"%s", section, json->item_sep);
1136     }
1137 }
1138
1139 static void json_print_section_footer(WriterContext *wctx, const char *section)
1140 {
1141     JSONContext *json = wctx->priv;
1142
1143     printf("%s", json->item_start_end);
1144     json->indent_level--;
1145     if (!json->compact)
1146         JSON_INDENT();
1147     printf("}");
1148 }
1149
1150 static inline void json_print_item_str(WriterContext *wctx,
1151                                        const char *key, const char *value)
1152 {
1153     AVBPrint buf;
1154
1155     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1156     printf("\"%s\":", json_escape_str(&buf, key,   wctx));
1157     av_bprint_clear(&buf);
1158     printf(" \"%s\"", json_escape_str(&buf, value, wctx));
1159     av_bprint_finalize(&buf, NULL);
1160 }
1161
1162 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
1163 {
1164     JSONContext *json = wctx->priv;
1165
1166     if (wctx->nb_item) printf("%s", json->item_sep);
1167     if (!json->compact)
1168         JSON_INDENT();
1169     json_print_item_str(wctx, key, value);
1170 }
1171
1172 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
1173 {
1174     JSONContext *json = wctx->priv;
1175     AVBPrint buf;
1176
1177     if (wctx->nb_item) printf("%s", json->item_sep);
1178     if (!json->compact)
1179         JSON_INDENT();
1180
1181     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1182     printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
1183     av_bprint_finalize(&buf, NULL);
1184 }
1185
1186 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
1187 {
1188     JSONContext *json = wctx->priv;
1189     AVDictionaryEntry *tag = NULL;
1190     int is_first = 1;
1191     if (!dict)
1192         return;
1193     printf("%s", json->item_sep);
1194     if (!json->compact)
1195         JSON_INDENT();
1196     printf("\"tags\": {%s", json->item_start_end);
1197     json->indent_level++;
1198     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1199         if (is_first) is_first = 0;
1200         else          printf("%s", json->item_sep);
1201         if (!json->compact)
1202             JSON_INDENT();
1203         json_print_item_str(wctx, tag->key, tag->value);
1204     }
1205     json->indent_level--;
1206     printf("%s", json->item_start_end);
1207     if (!json->compact)
1208         JSON_INDENT();
1209     printf("}");
1210 }
1211
1212 static const Writer json_writer = {
1213     .name                 = "json",
1214     .priv_size            = sizeof(JSONContext),
1215     .init                 = json_init,
1216     .print_header         = json_print_header,
1217     .print_footer         = json_print_footer,
1218     .print_chapter_header = json_print_chapter_header,
1219     .print_chapter_footer = json_print_chapter_footer,
1220     .print_section_header = json_print_section_header,
1221     .print_section_footer = json_print_section_footer,
1222     .print_integer        = json_print_int,
1223     .print_string         = json_print_str,
1224     .show_tags            = json_show_tags,
1225     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1226     .priv_class           = &json_class,
1227 };
1228
1229 /* XML output */
1230
1231 typedef struct {
1232     const AVClass *class;
1233     int within_tag;
1234     int indent_level;
1235     int fully_qualified;
1236     int xsd_strict;
1237 } XMLContext;
1238
1239 #undef OFFSET
1240 #define OFFSET(x) offsetof(XMLContext, x)
1241
1242 static const AVOption xml_options[] = {
1243     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1244     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1245     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1246     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1247     {NULL},
1248 };
1249
1250 DEFINE_WRITER_CLASS(xml);
1251
1252 static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
1253 {
1254     XMLContext *xml = wctx->priv;
1255
1256     if (xml->xsd_strict) {
1257         xml->fully_qualified = 1;
1258 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
1259         if (opt) {                                                      \
1260             av_log(wctx, AV_LOG_ERROR,                                  \
1261                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1262                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1263             return AVERROR(EINVAL);                                     \
1264         }
1265         CHECK_COMPLIANCE(show_private_data, "private");
1266         CHECK_COMPLIANCE(show_value_unit,   "unit");
1267         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
1268
1269         if (do_show_frames && do_show_packets) {
1270             av_log(wctx, AV_LOG_ERROR,
1271                    "Interleaved frames and packets are not allowed in XSD. "
1272                    "Select only one between the -show_frames and the -show_packets options.\n");
1273             return AVERROR(EINVAL);
1274         }
1275     }
1276
1277     return 0;
1278 }
1279
1280 static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1281 {
1282     const char *p;
1283
1284     for (p = src; *p; p++) {
1285         switch (*p) {
1286         case '&' : av_bprintf(dst, "%s", "&amp;");  break;
1287         case '<' : av_bprintf(dst, "%s", "&lt;");   break;
1288         case '>' : av_bprintf(dst, "%s", "&gt;");   break;
1289         case '\"': av_bprintf(dst, "%s", "&quot;"); break;
1290         case '\'': av_bprintf(dst, "%s", "&apos;"); break;
1291         default: av_bprint_chars(dst, *p, 1);
1292         }
1293     }
1294
1295     return dst->str;
1296 }
1297
1298 static void xml_print_header(WriterContext *wctx)
1299 {
1300     XMLContext *xml = wctx->priv;
1301     const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1302         "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1303         "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1304
1305     printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1306     printf("<%sffprobe%s>\n",
1307            xml->fully_qualified ? "ffprobe:" : "",
1308            xml->fully_qualified ? qual : "");
1309
1310     xml->indent_level++;
1311 }
1312
1313 static void xml_print_footer(WriterContext *wctx)
1314 {
1315     XMLContext *xml = wctx->priv;
1316
1317     xml->indent_level--;
1318     printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1319 }
1320
1321 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1322
1323 static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
1324 {
1325     XMLContext *xml = wctx->priv;
1326
1327     if (wctx->nb_chapter)
1328         printf("\n");
1329     if (wctx->multiple_sections) {
1330         XML_INDENT(); printf("<%s>\n", chapter);
1331         xml->indent_level++;
1332     }
1333 }
1334
1335 static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
1336 {
1337     XMLContext *xml = wctx->priv;
1338
1339     if (wctx->multiple_sections) {
1340         xml->indent_level--;
1341         XML_INDENT(); printf("</%s>\n", chapter);
1342     }
1343 }
1344
1345 static void xml_print_section_header(WriterContext *wctx, const char *section)
1346 {
1347     XMLContext *xml = wctx->priv;
1348
1349     XML_INDENT(); printf("<%s ", section);
1350     xml->within_tag = 1;
1351 }
1352
1353 static void xml_print_section_footer(WriterContext *wctx, const char *section)
1354 {
1355     XMLContext *xml = wctx->priv;
1356
1357     if (xml->within_tag)
1358         printf("/>\n");
1359     else {
1360         XML_INDENT(); printf("</%s>\n", section);
1361     }
1362 }
1363
1364 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1365 {
1366     AVBPrint buf;
1367
1368     if (wctx->nb_item)
1369         printf(" ");
1370     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1371     printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
1372     av_bprint_finalize(&buf, NULL);
1373 }
1374
1375 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1376 {
1377     if (wctx->nb_item)
1378         printf(" ");
1379     printf("%s=\"%lld\"", key, value);
1380 }
1381
1382 static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
1383 {
1384     XMLContext *xml = wctx->priv;
1385     AVDictionaryEntry *tag = NULL;
1386     int is_first = 1;
1387     AVBPrint buf;
1388
1389     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1390     xml->indent_level++;
1391     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1392         if (is_first) {
1393             /* close section tag */
1394             printf(">\n");
1395             xml->within_tag = 0;
1396             is_first = 0;
1397         }
1398         XML_INDENT();
1399
1400         av_bprint_clear(&buf);
1401         printf("<tag key=\"%s\"", xml_escape_str(&buf, tag->key, wctx));
1402         av_bprint_clear(&buf);
1403         printf(" value=\"%s\"/>\n", xml_escape_str(&buf, tag->value, wctx));
1404     }
1405     av_bprint_finalize(&buf, NULL);
1406     xml->indent_level--;
1407 }
1408
1409 static Writer xml_writer = {
1410     .name                 = "xml",
1411     .priv_size            = sizeof(XMLContext),
1412     .init                 = xml_init,
1413     .print_header         = xml_print_header,
1414     .print_footer         = xml_print_footer,
1415     .print_chapter_header = xml_print_chapter_header,
1416     .print_chapter_footer = xml_print_chapter_footer,
1417     .print_section_header = xml_print_section_header,
1418     .print_section_footer = xml_print_section_footer,
1419     .print_integer        = xml_print_int,
1420     .print_string         = xml_print_str,
1421     .show_tags            = xml_show_tags,
1422     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1423     .priv_class           = &xml_class,
1424 };
1425
1426 static void writer_register_all(void)
1427 {
1428     static int initialized;
1429
1430     if (initialized)
1431         return;
1432     initialized = 1;
1433
1434     writer_register(&default_writer);
1435     writer_register(&compact_writer);
1436     writer_register(&csv_writer);
1437     writer_register(&flat_writer);
1438     writer_register(&ini_writer);
1439     writer_register(&json_writer);
1440     writer_register(&xml_writer);
1441 }
1442
1443 #define print_fmt(k, f, ...) do {              \
1444     av_bprint_clear(&pbuf);                    \
1445     av_bprintf(&pbuf, f, __VA_ARGS__);         \
1446     writer_print_string(w, k, pbuf.str, 0);    \
1447 } while (0)
1448
1449 #define print_int(k, v)         writer_print_integer(w, k, v)
1450 #define print_q(k, v, s)        writer_print_rational(w, k, v, s)
1451 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1452 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1453 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb, 0)
1454 #define print_ts(k, v)          writer_print_ts(w, k, v, 0)
1455 #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
1456 #define print_duration_ts(k, v)       writer_print_ts(w, k, v, 1)
1457 #define print_val(k, v, u) do {                                     \
1458     struct unit_value uv;                                           \
1459     uv.val.i = v;                                                   \
1460     uv.unit = u;                                                    \
1461     writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
1462 } while (0)
1463
1464 #define print_section_header(s) writer_print_section_header(w, s)
1465 #define print_section_footer(s) writer_print_section_footer(w, s)
1466 #define show_tags(metadata)     writer_show_tags(w, metadata)
1467
1468 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1469 {
1470     char val_str[128];
1471     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1472     AVBPrint pbuf;
1473     const char *s;
1474
1475     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1476
1477     print_section_header("packet");
1478     s = av_get_media_type_string(st->codec->codec_type);
1479     if (s) print_str    ("codec_type", s);
1480     else   print_str_opt("codec_type", "unknown");
1481     print_int("stream_index",     pkt->stream_index);
1482     print_ts  ("pts",             pkt->pts);
1483     print_time("pts_time",        pkt->pts, &st->time_base);
1484     print_ts  ("dts",             pkt->dts);
1485     print_time("dts_time",        pkt->dts, &st->time_base);
1486     print_duration_ts("duration",        pkt->duration);
1487     print_duration_time("duration_time", pkt->duration, &st->time_base);
1488     print_duration_ts("convergence_duration", pkt->convergence_duration);
1489     print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
1490     print_val("size",             pkt->size, unit_byte_str);
1491     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1492     else                print_str_opt("pos", "N/A");
1493     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1494     if (do_show_data)
1495         writer_print_data(w, "data", pkt->data, pkt->size);
1496     print_section_footer("packet");
1497
1498     av_bprint_finalize(&pbuf, NULL);
1499     fflush(stdout);
1500 }
1501
1502 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
1503                        AVFormatContext *fmt_ctx)
1504 {
1505     AVBPrint pbuf;
1506     const char *s;
1507
1508     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1509
1510     print_section_header("frame");
1511
1512     s = av_get_media_type_string(stream->codec->codec_type);
1513     if (s) print_str    ("media_type", s);
1514     else   print_str_opt("media_type", "unknown");
1515     print_int("key_frame",              frame->key_frame);
1516     print_ts  ("pkt_pts",               frame->pkt_pts);
1517     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1518     print_ts  ("pkt_dts",               frame->pkt_dts);
1519     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1520     print_duration_ts  ("pkt_duration",      frame->pkt_duration);
1521     print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
1522     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1523     else                      print_str_opt("pkt_pos", "N/A");
1524
1525     switch (stream->codec->codec_type) {
1526         AVRational sar;
1527
1528     case AVMEDIA_TYPE_VIDEO:
1529         print_int("width",                  frame->width);
1530         print_int("height",                 frame->height);
1531         s = av_get_pix_fmt_name(frame->format);
1532         if (s) print_str    ("pix_fmt", s);
1533         else   print_str_opt("pix_fmt", "unknown");
1534         sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
1535         if (sar.num) {
1536             print_q("sample_aspect_ratio", sar, ':');
1537         } else {
1538             print_str_opt("sample_aspect_ratio", "N/A");
1539         }
1540         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1541         print_int("coded_picture_number",   frame->coded_picture_number);
1542         print_int("display_picture_number", frame->display_picture_number);
1543         print_int("interlaced_frame",       frame->interlaced_frame);
1544         print_int("top_field_first",        frame->top_field_first);
1545         print_int("repeat_pict",            frame->repeat_pict);
1546         print_int("reference",              frame->reference);
1547         break;
1548
1549     case AVMEDIA_TYPE_AUDIO:
1550         s = av_get_sample_fmt_name(frame->format);
1551         if (s) print_str    ("sample_fmt", s);
1552         else   print_str_opt("sample_fmt", "unknown");
1553         print_int("nb_samples",         frame->nb_samples);
1554         print_int("channels", av_frame_get_channels(frame));
1555         if (av_frame_get_channel_layout(frame)) {
1556             av_bprint_clear(&pbuf);
1557             av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
1558                                      av_frame_get_channel_layout(frame));
1559             print_str    ("channel_layout", pbuf.str);
1560         } else
1561             print_str_opt("channel_layout", "unknown");
1562         break;
1563     }
1564     show_tags(av_frame_get_metadata(frame));
1565
1566     print_section_footer("frame");
1567
1568     av_bprint_finalize(&pbuf, NULL);
1569     fflush(stdout);
1570 }
1571
1572 static av_always_inline int process_frame(WriterContext *w,
1573                                           AVFormatContext *fmt_ctx,
1574                                           AVFrame *frame, AVPacket *pkt)
1575 {
1576     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1577     int ret = 0, got_frame = 0;
1578
1579     avcodec_get_frame_defaults(frame);
1580     if (dec_ctx->codec) {
1581         switch (dec_ctx->codec_type) {
1582         case AVMEDIA_TYPE_VIDEO:
1583             ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
1584             break;
1585
1586         case AVMEDIA_TYPE_AUDIO:
1587             ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
1588             break;
1589         }
1590     }
1591
1592     if (ret < 0)
1593         return ret;
1594     ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
1595     pkt->data += ret;
1596     pkt->size -= ret;
1597     if (got_frame) {
1598         nb_streams_frames[pkt->stream_index]++;
1599         if (do_show_frames)
1600             show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
1601     }
1602     return got_frame;
1603 }
1604
1605 static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1606 {
1607     AVPacket pkt, pkt1;
1608     AVFrame frame;
1609     int i = 0;
1610
1611     av_init_packet(&pkt);
1612
1613     while (!av_read_frame(fmt_ctx, &pkt)) {
1614         if (do_read_packets) {
1615             if (do_show_packets)
1616                 show_packet(w, fmt_ctx, &pkt, i++);
1617             nb_streams_packets[pkt.stream_index]++;
1618         }
1619         if (do_read_frames) {
1620             pkt1 = pkt;
1621             while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
1622         }
1623         av_free_packet(&pkt);
1624     }
1625     av_init_packet(&pkt);
1626     pkt.data = NULL;
1627     pkt.size = 0;
1628     //Flush remaining frames that are cached in the decoder
1629     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1630         pkt.stream_index = i;
1631         if (do_read_frames)
1632             while (process_frame(w, fmt_ctx, &frame, &pkt) > 0);
1633     }
1634 }
1635
1636 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1637 {
1638     AVStream *stream = fmt_ctx->streams[stream_idx];
1639     AVCodecContext *dec_ctx;
1640     const AVCodec *dec;
1641     char val_str[128];
1642     const char *s;
1643     AVRational sar, dar;
1644     AVBPrint pbuf;
1645
1646     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1647
1648     print_section_header("stream");
1649
1650     print_int("index", stream->index);
1651
1652     if ((dec_ctx = stream->codec)) {
1653         const char *profile = NULL;
1654         dec = dec_ctx->codec;
1655         if (dec) {
1656             print_str("codec_name", dec->name);
1657             if (!do_bitexact) {
1658                 if (dec->long_name) print_str    ("codec_long_name", dec->long_name);
1659                 else                print_str_opt("codec_long_name", "unknown");
1660             }
1661         } else {
1662             print_str_opt("codec_name", "unknown");
1663             if (!do_bitexact) {
1664                 print_str_opt("codec_long_name", "unknown");
1665             }
1666         }
1667
1668         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
1669             print_str("profile", profile);
1670         else
1671             print_str_opt("profile", "unknown");
1672
1673         s = av_get_media_type_string(dec_ctx->codec_type);
1674         if (s) print_str    ("codec_type", s);
1675         else   print_str_opt("codec_type", "unknown");
1676         print_q("codec_time_base", dec_ctx->time_base, '/');
1677
1678         /* print AVI/FourCC tag */
1679         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1680         print_str("codec_tag_string",    val_str);
1681         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1682
1683         /* Print useful disposition */
1684         print_int("default", !!(stream->disposition & AV_DISPOSITION_DEFAULT));
1685         print_int("forced", !!(stream->disposition & AV_DISPOSITION_FORCED));
1686
1687         switch (dec_ctx->codec_type) {
1688         case AVMEDIA_TYPE_VIDEO:
1689             print_int("width",        dec_ctx->width);
1690             print_int("height",       dec_ctx->height);
1691             print_int("has_b_frames", dec_ctx->has_b_frames);
1692             sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
1693             if (sar.den) {
1694                 print_q("sample_aspect_ratio", sar, ':');
1695                 av_reduce(&dar.num, &dar.den,
1696                           dec_ctx->width  * sar.num,
1697                           dec_ctx->height * sar.den,
1698                           1024*1024);
1699                 print_q("display_aspect_ratio", dar, ':');
1700             } else {
1701                 print_str_opt("sample_aspect_ratio", "N/A");
1702                 print_str_opt("display_aspect_ratio", "N/A");
1703             }
1704             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1705             if (s) print_str    ("pix_fmt", s);
1706             else   print_str_opt("pix_fmt", "unknown");
1707             print_int("level",   dec_ctx->level);
1708             if (dec_ctx->timecode_frame_start >= 0) {
1709                 char tcbuf[AV_TIMECODE_STR_SIZE];
1710                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
1711                 print_str("timecode", tcbuf);
1712             } else {
1713                 print_str_opt("timecode", "N/A");
1714             }
1715             print_int("attached_pic",
1716                       !!(stream->disposition & AV_DISPOSITION_ATTACHED_PIC));
1717             break;
1718
1719         case AVMEDIA_TYPE_AUDIO:
1720             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1721             if (s) print_str    ("sample_fmt", s);
1722             else   print_str_opt("sample_fmt", "unknown");
1723             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1724             print_int("channels",        dec_ctx->channels);
1725             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1726             break;
1727         }
1728     } else {
1729         print_str_opt("codec_type", "unknown");
1730     }
1731     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1732         const AVOption *opt = NULL;
1733         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1734             uint8_t *str;
1735             if (opt->flags) continue;
1736             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1737                 print_str(opt->name, str);
1738                 av_free(str);
1739             }
1740         }
1741     }
1742
1743     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1744     else                                          print_str_opt("id", "N/A");
1745     print_q("r_frame_rate",   stream->r_frame_rate,   '/');
1746     print_q("avg_frame_rate", stream->avg_frame_rate, '/');
1747     print_q("time_base",      stream->time_base,      '/');
1748     print_ts  ("start_pts",   stream->start_time);
1749     print_time("start_time",  stream->start_time, &stream->time_base);
1750     print_ts  ("duration_ts", stream->duration);
1751     print_time("duration",    stream->duration, &stream->time_base);
1752     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
1753     else                       print_str_opt("bit_rate", "N/A");
1754     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1755     else                   print_str_opt("nb_frames", "N/A");
1756     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
1757     else                                print_str_opt("nb_read_frames", "N/A");
1758     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
1759     else                                print_str_opt("nb_read_packets", "N/A");
1760     if (do_show_data)
1761         writer_print_data(w, "extradata", dec_ctx->extradata,
1762                                           dec_ctx->extradata_size);
1763     show_tags(stream->metadata);
1764
1765     print_section_footer("stream");
1766     av_bprint_finalize(&pbuf, NULL);
1767     fflush(stdout);
1768 }
1769
1770 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1771 {
1772     int i;
1773     for (i = 0; i < fmt_ctx->nb_streams; i++)
1774         show_stream(w, fmt_ctx, i);
1775 }
1776
1777 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1778 {
1779     char val_str[128];
1780     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1781
1782     print_section_header("format");
1783     print_str("filename",         fmt_ctx->filename);
1784     print_int("nb_streams",       fmt_ctx->nb_streams);
1785     print_str("format_name",      fmt_ctx->iformat->name);
1786     if (!do_bitexact) {
1787         if (fmt_ctx->iformat->long_name) print_str    ("format_long_name", fmt_ctx->iformat->long_name);
1788         else                             print_str_opt("format_long_name", "unknown");
1789     }
1790     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1791     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1792     if (size >= 0) print_val    ("size", size, unit_byte_str);
1793     else           print_str_opt("size", "N/A");
1794     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1795     else                       print_str_opt("bit_rate", "N/A");
1796     show_tags(fmt_ctx->metadata);
1797     print_section_footer("format");
1798     fflush(stdout);
1799 }
1800
1801 static void show_error(WriterContext *w, int err)
1802 {
1803     char errbuf[128];
1804     const char *errbuf_ptr = errbuf;
1805
1806     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1807         errbuf_ptr = strerror(AVUNERROR(err));
1808
1809     writer_print_chapter_header(w, "error");
1810     print_section_header("error");
1811     print_int("code", err);
1812     print_str("string", errbuf_ptr);
1813     print_section_footer("error");
1814     writer_print_chapter_footer(w, "error");
1815 }
1816
1817 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1818 {
1819     int err, i;
1820     AVFormatContext *fmt_ctx = NULL;
1821     AVDictionaryEntry *t;
1822
1823     if ((err = avformat_open_input(&fmt_ctx, filename,
1824                                    iformat, &format_opts)) < 0) {
1825         print_error(filename, err);
1826         return err;
1827     }
1828     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1829         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1830         return AVERROR_OPTION_NOT_FOUND;
1831     }
1832
1833
1834     /* fill the streams in the format context */
1835     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1836         print_error(filename, err);
1837         return err;
1838     }
1839
1840     av_dump_format(fmt_ctx, 0, filename, 0);
1841
1842     /* bind a decoder to each input stream */
1843     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1844         AVStream *stream = fmt_ctx->streams[i];
1845         AVCodec *codec;
1846
1847         if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
1848             av_log(NULL, AV_LOG_ERROR,
1849                    "Failed to probe codec for input stream %d\n",
1850                     stream->index);
1851         } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1852             av_log(NULL, AV_LOG_ERROR,
1853                     "Unsupported codec with id %d for input stream %d\n",
1854                     stream->codec->codec_id, stream->index);
1855         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1856             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1857                    stream->index);
1858         }
1859     }
1860
1861     *fmt_ctx_ptr = fmt_ctx;
1862     return 0;
1863 }
1864
1865 static void close_input_file(AVFormatContext **ctx_ptr)
1866 {
1867     int i;
1868     AVFormatContext *fmt_ctx = *ctx_ptr;
1869
1870     /* close decoder for each stream */
1871     for (i = 0; i < fmt_ctx->nb_streams; i++)
1872         if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
1873             avcodec_close(fmt_ctx->streams[i]->codec);
1874
1875     avformat_close_input(ctx_ptr);
1876 }
1877
1878 #define PRINT_CHAPTER(name) do {                                        \
1879     if (do_show_ ## name) {                                             \
1880         writer_print_chapter_header(wctx, #name);                       \
1881         show_ ## name (wctx, fmt_ctx);                                  \
1882         writer_print_chapter_footer(wctx, #name);                       \
1883     }                                                                   \
1884 } while (0)
1885
1886 static int probe_file(WriterContext *wctx, const char *filename)
1887 {
1888     AVFormatContext *fmt_ctx;
1889     int ret;
1890
1891     do_read_frames = do_show_frames || do_count_frames;
1892     do_read_packets = do_show_packets || do_count_packets;
1893
1894     ret = open_input_file(&fmt_ctx, filename);
1895     if (ret >= 0) {
1896         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
1897         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
1898         if (do_read_frames || do_read_packets) {
1899             const char *chapter;
1900             if (do_show_frames && do_show_packets &&
1901                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1902                 chapter = "packets_and_frames";
1903             else if (do_show_packets && !do_show_frames)
1904                 chapter = "packets";
1905             else // (!do_show_packets && do_show_frames)
1906                 chapter = "frames";
1907             if (do_show_frames || do_show_packets)
1908                 writer_print_chapter_header(wctx, chapter);
1909             read_packets(wctx, fmt_ctx);
1910             if (do_show_frames || do_show_packets)
1911                 writer_print_chapter_footer(wctx, chapter);
1912         }
1913         PRINT_CHAPTER(streams);
1914         PRINT_CHAPTER(format);
1915         close_input_file(&fmt_ctx);
1916         av_freep(&nb_streams_frames);
1917         av_freep(&nb_streams_packets);
1918     }
1919     return ret;
1920 }
1921
1922 static void show_usage(void)
1923 {
1924     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1925     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1926     av_log(NULL, AV_LOG_INFO, "\n");
1927 }
1928
1929 static void ffprobe_show_program_version(WriterContext *w)
1930 {
1931     AVBPrint pbuf;
1932     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1933
1934     writer_print_chapter_header(w, "program_version");
1935     print_section_header("program_version");
1936     print_str("version", FFMPEG_VERSION);
1937     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1938               program_birth_year, this_year);
1939     print_str("build_date", __DATE__);
1940     print_str("build_time", __TIME__);
1941     print_str("compiler_ident", CC_IDENT);
1942     print_str("configuration", FFMPEG_CONFIGURATION);
1943     print_section_footer("program_version");
1944     writer_print_chapter_footer(w, "program_version");
1945
1946     av_bprint_finalize(&pbuf, NULL);
1947 }
1948
1949 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1950     do {                                                                \
1951         if (CONFIG_##LIBNAME) {                                         \
1952             unsigned int version = libname##_version();                 \
1953             print_section_header("library_version");                    \
1954             print_str("name",    "lib" #libname);                       \
1955             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1956             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1957             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1958             print_int("version", version);                              \
1959             print_section_footer("library_version");                    \
1960         }                                                               \
1961     } while (0)
1962
1963 static void ffprobe_show_library_versions(WriterContext *w)
1964 {
1965     writer_print_chapter_header(w, "library_versions");
1966     SHOW_LIB_VERSION(avutil,     AVUTIL);
1967     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1968     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1969     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1970     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1971     SHOW_LIB_VERSION(swscale,    SWSCALE);
1972     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
1973     SHOW_LIB_VERSION(postproc,   POSTPROC);
1974     writer_print_chapter_footer(w, "library_versions");
1975 }
1976
1977 static int opt_format(void *optctx, const char *opt, const char *arg)
1978 {
1979     iformat = av_find_input_format(arg);
1980     if (!iformat) {
1981         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1982         return AVERROR(EINVAL);
1983     }
1984     return 0;
1985 }
1986
1987 static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
1988 {
1989     do_show_format = 1;
1990     av_dict_set(&fmt_entries_to_show, arg, "", 0);
1991     return 0;
1992 }
1993
1994 static void opt_input_file(void *optctx, const char *arg)
1995 {
1996     if (input_filename) {
1997         av_log(NULL, AV_LOG_ERROR,
1998                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1999                 arg, input_filename);
2000         exit(1);
2001     }
2002     if (!strcmp(arg, "-"))
2003         arg = "pipe:";
2004     input_filename = arg;
2005 }
2006
2007 static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
2008 {
2009     opt_input_file(optctx, arg);
2010     return 0;
2011 }
2012
2013 void show_help_default(const char *opt, const char *arg)
2014 {
2015     av_log_set_callback(log_callback_help);
2016     show_usage();
2017     show_help_options(options, "Main options:", 0, 0, 0);
2018     printf("\n");
2019
2020     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
2021 }
2022
2023 static int opt_pretty(void *optctx, const char *opt, const char *arg)
2024 {
2025     show_value_unit              = 1;
2026     use_value_prefix             = 1;
2027     use_byte_value_binary_prefix = 1;
2028     use_value_sexagesimal_format = 1;
2029     return 0;
2030 }
2031
2032 static int opt_show_versions(const char *opt, const char *arg)
2033 {
2034     do_show_program_version  = 1;
2035     do_show_library_versions = 1;
2036     return 0;
2037 }
2038
2039 static const OptionDef real_options[] = {
2040 #include "cmdutils_common_opts.h"
2041     { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
2042     { "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
2043     { "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
2044     { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
2045       "use binary prefixes for byte units" },
2046     { "sexagesimal", OPT_BOOL,  {&use_value_sexagesimal_format},
2047       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
2048     { "pretty", 0, {.func_arg = opt_pretty},
2049       "prettify the format of displayed values, make it more human readable" },
2050     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
2051       "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
2052     { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
2053     { "show_data",    OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
2054     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
2055     { "show_format",  OPT_BOOL, {&do_show_format} , "show format/container info" },
2056     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
2057     { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
2058       "show a particular entry from the format/container info", "entry" },
2059     { "show_packets", OPT_BOOL, {&do_show_packets}, "show packets info" },
2060     { "show_streams", OPT_BOOL, {&do_show_streams}, "show streams info" },
2061     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
2062     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
2063     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
2064     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
2065     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
2066     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
2067     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
2068     { "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
2069     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
2070     { "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
2071     { NULL, },
2072 };
2073
2074 int main(int argc, char **argv)
2075 {
2076     const Writer *w;
2077     WriterContext *wctx;
2078     char *buf;
2079     char *w_name = NULL, *w_args = NULL;
2080     int ret;
2081
2082     av_log_set_flags(AV_LOG_SKIP_REPEATED);
2083     options = real_options;
2084     parse_loglevel(argc, argv, options);
2085     av_register_all();
2086     avformat_network_init();
2087     init_opts();
2088 #if CONFIG_AVDEVICE
2089     avdevice_register_all();
2090 #endif
2091
2092     show_banner(argc, argv, options);
2093     parse_options(NULL, argc, argv, options, opt_input_file);
2094
2095     if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
2096         av_log(NULL, AV_LOG_ERROR,
2097                "-bitexact and -show_program_version or -show_library_versions "
2098                "options are incompatible\n");
2099         ret = AVERROR(EINVAL);
2100         goto end;
2101     }
2102
2103     writer_register_all();
2104
2105     if (!print_format)
2106         print_format = av_strdup("default");
2107     w_name = av_strtok(print_format, "=", &buf);
2108     w_args = buf;
2109
2110     w = writer_get_by_name(w_name);
2111     if (!w) {
2112         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
2113         ret = AVERROR(EINVAL);
2114         goto end;
2115     }
2116
2117     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
2118         writer_print_header(wctx);
2119
2120         if (do_show_program_version)
2121             ffprobe_show_program_version(wctx);
2122         if (do_show_library_versions)
2123             ffprobe_show_library_versions(wctx);
2124
2125         if (!input_filename &&
2126             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
2127              (!do_show_program_version && !do_show_library_versions))) {
2128             show_usage();
2129             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
2130             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
2131             ret = AVERROR(EINVAL);
2132         } else if (input_filename) {
2133             ret = probe_file(wctx, input_filename);
2134             if (ret < 0 && do_show_error)
2135                 show_error(wctx, ret);
2136         }
2137
2138         writer_print_footer(wctx);
2139         writer_close(&wctx);
2140     }
2141
2142 end:
2143     av_freep(&print_format);
2144
2145     uninit_opts();
2146     av_dict_free(&fmt_entries_to_show);
2147
2148     avformat_network_deinit();
2149
2150     return ret;
2151 }