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