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