]> 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/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, int is_duration)
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 ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
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, int is_duration)
340 {
341     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
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, 0)
1514 #define print_ts(k, v)          writer_print_ts(w, k, v, 0)
1515 #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
1516 #define print_duration_ts(k, v)       writer_print_ts(w, k, v, 1)
1517 #define print_val(k, v, u)      writer_print_string(w, k, \
1518     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
1519 #define print_section_header(s) writer_print_section_header(w, s)
1520 #define print_section_footer(s) writer_print_section_footer(w, s)
1521 #define show_tags(metadata)     writer_show_tags(w, metadata)
1522
1523 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1524 {
1525     char val_str[128];
1526     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1527     AVBPrint pbuf;
1528     const char *s;
1529
1530     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1531
1532     print_section_header("packet");
1533     s = av_get_media_type_string(st->codec->codec_type);
1534     if (s) print_str    ("codec_type", s);
1535     else   print_str_opt("codec_type", "unknown");
1536     print_int("stream_index",     pkt->stream_index);
1537     print_ts  ("pts",             pkt->pts);
1538     print_time("pts_time",        pkt->pts, &st->time_base);
1539     print_ts  ("dts",             pkt->dts);
1540     print_time("dts_time",        pkt->dts, &st->time_base);
1541     print_duration_ts("duration",        pkt->duration);
1542     print_duration_time("duration_time", pkt->duration, &st->time_base);
1543     print_val("size",             pkt->size, unit_byte_str);
1544     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1545     else                print_str_opt("pos", "N/A");
1546     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1547     print_section_footer("packet");
1548
1549     av_bprint_finalize(&pbuf, NULL);
1550     fflush(stdout);
1551 }
1552
1553 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
1554 {
1555     AVBPrint pbuf;
1556     const char *s;
1557
1558     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1559
1560     print_section_header("frame");
1561
1562     s = av_get_media_type_string(stream->codec->codec_type);
1563     if (s) print_str    ("media_type", s);
1564     else   print_str_opt("media_type", "unknown");
1565     print_int("key_frame",              frame->key_frame);
1566     print_ts  ("pkt_pts",               frame->pkt_pts);
1567     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1568     print_ts  ("pkt_dts",               frame->pkt_dts);
1569     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1570     print_duration_ts  ("pkt_duration",      frame->pkt_duration);
1571     print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
1572     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1573     else                      print_str_opt("pkt_pos", "N/A");
1574
1575     switch (stream->codec->codec_type) {
1576     case AVMEDIA_TYPE_VIDEO:
1577         print_int("width",                  frame->width);
1578         print_int("height",                 frame->height);
1579         s = av_get_pix_fmt_name(frame->format);
1580         if (s) print_str    ("pix_fmt", s);
1581         else   print_str_opt("pix_fmt", "unknown");
1582         if (frame->sample_aspect_ratio.num) {
1583             print_fmt("sample_aspect_ratio", "%d:%d",
1584                       frame->sample_aspect_ratio.num,
1585                       frame->sample_aspect_ratio.den);
1586         } else {
1587             print_str_opt("sample_aspect_ratio", "N/A");
1588         }
1589         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1590         print_int("coded_picture_number",   frame->coded_picture_number);
1591         print_int("display_picture_number", frame->display_picture_number);
1592         print_int("interlaced_frame",       frame->interlaced_frame);
1593         print_int("top_field_first",        frame->top_field_first);
1594         print_int("repeat_pict",            frame->repeat_pict);
1595         print_int("reference",              frame->reference);
1596         break;
1597
1598     case AVMEDIA_TYPE_AUDIO:
1599         s = av_get_sample_fmt_name(frame->format);
1600         if (s) print_str    ("sample_fmt", s);
1601         else   print_str_opt("sample_fmt", "unknown");
1602         print_int("nb_samples",         frame->nb_samples);
1603         break;
1604     }
1605
1606     print_section_footer("frame");
1607
1608     av_bprint_finalize(&pbuf, NULL);
1609     fflush(stdout);
1610 }
1611
1612 static av_always_inline int get_decoded_frame(AVFormatContext *fmt_ctx,
1613                                               AVFrame *frame, int *got_frame,
1614                                               AVPacket *pkt)
1615 {
1616     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1617     int ret = 0;
1618
1619     *got_frame = 0;
1620     switch (dec_ctx->codec_type) {
1621     case AVMEDIA_TYPE_VIDEO:
1622         ret = avcodec_decode_video2(dec_ctx, frame, got_frame, pkt);
1623         break;
1624
1625     case AVMEDIA_TYPE_AUDIO:
1626         ret = avcodec_decode_audio4(dec_ctx, frame, got_frame, pkt);
1627         break;
1628     }
1629
1630     return ret;
1631 }
1632
1633 static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1634 {
1635     AVPacket pkt, pkt1;
1636     AVFrame frame;
1637     int i = 0, ret, got_frame;
1638
1639     av_init_packet(&pkt);
1640
1641     while (!av_read_frame(fmt_ctx, &pkt)) {
1642         if (do_read_packets) {
1643             if (do_show_packets)
1644                 show_packet(w, fmt_ctx, &pkt, i++);
1645             nb_streams_packets[pkt.stream_index]++;
1646         }
1647         if (do_read_frames) {
1648             pkt1 = pkt;
1649             while (pkt1.size) {
1650                 avcodec_get_frame_defaults(&frame);
1651                 ret = get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt1);
1652                 if (ret < 0 || !got_frame)
1653                     break;
1654                 if (do_show_frames)
1655                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1656                 pkt1.data += ret;
1657                 pkt1.size -= ret;
1658                 nb_streams_frames[pkt.stream_index]++;
1659             }
1660         }
1661         av_free_packet(&pkt);
1662     }
1663     av_init_packet(&pkt);
1664     pkt.data = NULL;
1665     pkt.size = 0;
1666     //Flush remaining frames that are cached in the decoder
1667     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1668         pkt.stream_index = i;
1669         while (get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt) >= 0 && got_frame) {
1670             if (do_read_frames) {
1671                 if (do_show_frames)
1672                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1673                 nb_streams_frames[pkt.stream_index]++;
1674             }
1675         }
1676     }
1677 }
1678
1679 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1680 {
1681     AVStream *stream = fmt_ctx->streams[stream_idx];
1682     AVCodecContext *dec_ctx;
1683     AVCodec *dec;
1684     char val_str[128];
1685     const char *s;
1686     AVRational display_aspect_ratio;
1687     AVBPrint pbuf;
1688
1689     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1690
1691     print_section_header("stream");
1692
1693     print_int("index", stream->index);
1694
1695     if ((dec_ctx = stream->codec)) {
1696         const char *profile = NULL;
1697         if ((dec = dec_ctx->codec)) {
1698             print_str("codec_name",      dec->name);
1699             print_str("codec_long_name", dec->long_name);
1700         } else {
1701             print_str_opt("codec_name",      "unknown");
1702             print_str_opt("codec_long_name", "unknown");
1703         }
1704
1705         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
1706             print_str("profile", profile);
1707         else
1708             print_str_opt("profile", "unknown");
1709
1710         s = av_get_media_type_string(dec_ctx->codec_type);
1711         if (s) print_str    ("codec_type", s);
1712         else   print_str_opt("codec_type", "unknown");
1713         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
1714
1715         /* print AVI/FourCC tag */
1716         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1717         print_str("codec_tag_string",    val_str);
1718         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1719
1720         switch (dec_ctx->codec_type) {
1721         case AVMEDIA_TYPE_VIDEO:
1722             print_int("width",        dec_ctx->width);
1723             print_int("height",       dec_ctx->height);
1724             print_int("has_b_frames", dec_ctx->has_b_frames);
1725             if (dec_ctx->sample_aspect_ratio.num) {
1726                 print_fmt("sample_aspect_ratio", "%d:%d",
1727                           dec_ctx->sample_aspect_ratio.num,
1728                           dec_ctx->sample_aspect_ratio.den);
1729                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1730                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
1731                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
1732                           1024*1024);
1733                 print_fmt("display_aspect_ratio", "%d:%d",
1734                           display_aspect_ratio.num,
1735                           display_aspect_ratio.den);
1736             } else {
1737                 print_str_opt("sample_aspect_ratio", "N/A");
1738                 print_str_opt("display_aspect_ratio", "N/A");
1739             }
1740             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1741             if (s) print_str    ("pix_fmt", s);
1742             else   print_str_opt("pix_fmt", "unknown");
1743             print_int("level",   dec_ctx->level);
1744             if (dec_ctx->timecode_frame_start >= 0) {
1745                 char tcbuf[AV_TIMECODE_STR_SIZE];
1746                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
1747                 print_str("timecode", tcbuf);
1748             } else {
1749                 print_str_opt("timecode", "N/A");
1750             }
1751             break;
1752
1753         case AVMEDIA_TYPE_AUDIO:
1754             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1755             if (s) print_str    ("sample_fmt", s);
1756             else   print_str_opt("sample_fmt", "unknown");
1757             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1758             print_int("channels",        dec_ctx->channels);
1759             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1760             break;
1761         }
1762     } else {
1763         print_str_opt("codec_type", "unknown");
1764     }
1765     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1766         const AVOption *opt = NULL;
1767         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1768             uint8_t *str;
1769             if (opt->flags) continue;
1770             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1771                 print_str(opt->name, str);
1772                 av_free(str);
1773             }
1774         }
1775     }
1776
1777     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1778     else                                          print_str_opt("id", "N/A");
1779     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1780     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1781     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1782     print_time("start_time",    stream->start_time, &stream->time_base);
1783     print_time("duration",      stream->duration,   &stream->time_base);
1784     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
1785     else                       print_str_opt("bit_rate", "N/A");
1786     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1787     else                   print_str_opt("nb_frames", "N/A");
1788     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
1789     else                                print_str_opt("nb_read_frames", "N/A");
1790     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
1791     else                                print_str_opt("nb_read_packets", "N/A");
1792     show_tags(stream->metadata);
1793
1794     print_section_footer("stream");
1795     av_bprint_finalize(&pbuf, NULL);
1796     fflush(stdout);
1797 }
1798
1799 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1800 {
1801     int i;
1802     for (i = 0; i < fmt_ctx->nb_streams; i++)
1803         show_stream(w, fmt_ctx, i);
1804 }
1805
1806 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1807 {
1808     char val_str[128];
1809     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1810
1811     print_section_header("format");
1812     print_str("filename",         fmt_ctx->filename);
1813     print_int("nb_streams",       fmt_ctx->nb_streams);
1814     print_str("format_name",      fmt_ctx->iformat->name);
1815     print_str("format_long_name", fmt_ctx->iformat->long_name);
1816     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1817     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1818     if (size >= 0) print_val    ("size", size, unit_byte_str);
1819     else           print_str_opt("size", "N/A");
1820     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1821     else                       print_str_opt("bit_rate", "N/A");
1822     show_tags(fmt_ctx->metadata);
1823     print_section_footer("format");
1824     fflush(stdout);
1825 }
1826
1827 static void show_error(WriterContext *w, int err)
1828 {
1829     char errbuf[128];
1830     const char *errbuf_ptr = errbuf;
1831
1832     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1833         errbuf_ptr = strerror(AVUNERROR(err));
1834
1835     writer_print_chapter_header(w, "error");
1836     print_section_header("error");
1837     print_int("code", err);
1838     print_str("string", errbuf_ptr);
1839     print_section_footer("error");
1840     writer_print_chapter_footer(w, "error");
1841 }
1842
1843 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1844 {
1845     int err, i;
1846     AVFormatContext *fmt_ctx = NULL;
1847     AVDictionaryEntry *t;
1848
1849     if ((err = avformat_open_input(&fmt_ctx, filename,
1850                                    iformat, &format_opts)) < 0) {
1851         print_error(filename, err);
1852         return err;
1853     }
1854     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1855         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1856         return AVERROR_OPTION_NOT_FOUND;
1857     }
1858
1859
1860     /* fill the streams in the format context */
1861     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1862         print_error(filename, err);
1863         return err;
1864     }
1865
1866     av_dump_format(fmt_ctx, 0, filename, 0);
1867
1868     /* bind a decoder to each input stream */
1869     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1870         AVStream *stream = fmt_ctx->streams[i];
1871         AVCodec *codec;
1872
1873         if (stream->codec->codec_id == CODEC_ID_PROBE) {
1874             av_log(NULL, AV_LOG_ERROR,
1875                    "Failed to probe codec for input stream %d\n",
1876                     stream->index);
1877         } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1878             av_log(NULL, AV_LOG_ERROR,
1879                     "Unsupported codec with id %d for input stream %d\n",
1880                     stream->codec->codec_id, stream->index);
1881         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1882             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1883                    stream->index);
1884         }
1885     }
1886
1887     *fmt_ctx_ptr = fmt_ctx;
1888     return 0;
1889 }
1890
1891 static void close_input_file(AVFormatContext **ctx_ptr)
1892 {
1893     int i;
1894     AVFormatContext *fmt_ctx = *ctx_ptr;
1895
1896     /* close decoder for each stream */
1897     for (i = 0; i < fmt_ctx->nb_streams; i++)
1898         if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
1899             avcodec_close(fmt_ctx->streams[i]->codec);
1900
1901     avformat_close_input(ctx_ptr);
1902 }
1903
1904 #define PRINT_CHAPTER(name) do {                                        \
1905     if (do_show_ ## name) {                                             \
1906         writer_print_chapter_header(wctx, #name);                       \
1907         show_ ## name (wctx, fmt_ctx);                                  \
1908         writer_print_chapter_footer(wctx, #name);                       \
1909     }                                                                   \
1910 } while (0)
1911
1912 static int probe_file(WriterContext *wctx, const char *filename)
1913 {
1914     AVFormatContext *fmt_ctx;
1915     int ret;
1916
1917     do_read_frames = do_show_frames || do_count_frames;
1918     do_read_packets = do_show_packets || do_count_packets;
1919
1920     ret = open_input_file(&fmt_ctx, filename);
1921     if (ret >= 0) {
1922         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
1923         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
1924         if (do_read_frames || do_read_packets) {
1925             const char *chapter;
1926             if (do_show_frames && do_show_packets &&
1927                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1928                 chapter = "packets_and_frames";
1929             else if (do_show_packets && !do_show_frames)
1930                 chapter = "packets";
1931             else // (!do_show_packets && do_show_frames)
1932                 chapter = "frames";
1933             if (do_show_frames || do_show_packets)
1934                 writer_print_chapter_header(wctx, chapter);
1935             read_packets(wctx, fmt_ctx);
1936             if (do_show_frames || do_show_packets)
1937                 writer_print_chapter_footer(wctx, chapter);
1938         }
1939         PRINT_CHAPTER(streams);
1940         PRINT_CHAPTER(format);
1941         close_input_file(&fmt_ctx);
1942         av_freep(&nb_streams_frames);
1943         av_freep(&nb_streams_packets);
1944     }
1945     return ret;
1946 }
1947
1948 static void show_usage(void)
1949 {
1950     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1951     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1952     av_log(NULL, AV_LOG_INFO, "\n");
1953 }
1954
1955 static void ffprobe_show_program_version(WriterContext *w)
1956 {
1957     AVBPrint pbuf;
1958     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1959
1960     writer_print_chapter_header(w, "program_version");
1961     print_section_header("program_version");
1962     print_str("version", FFMPEG_VERSION);
1963     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1964               program_birth_year, this_year);
1965     print_str("build_date", __DATE__);
1966     print_str("build_time", __TIME__);
1967     print_str("compiler_type", CC_TYPE);
1968     print_str("compiler_version", CC_VERSION);
1969     print_str("configuration", FFMPEG_CONFIGURATION);
1970     print_section_footer("program_version");
1971     writer_print_chapter_footer(w, "program_version");
1972
1973     av_bprint_finalize(&pbuf, NULL);
1974 }
1975
1976 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1977     do {                                                                \
1978         if (CONFIG_##LIBNAME) {                                         \
1979             unsigned int version = libname##_version();                 \
1980             print_section_header("library_version");                    \
1981             print_str("name",    "lib" #libname);                       \
1982             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1983             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1984             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1985             print_int("version", version);                              \
1986             print_section_footer("library_version");                    \
1987         }                                                               \
1988     } while (0)
1989
1990 static void ffprobe_show_library_versions(WriterContext *w)
1991 {
1992     writer_print_chapter_header(w, "library_versions");
1993     SHOW_LIB_VERSION(avutil,     AVUTIL);
1994     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1995     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1996     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1997     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1998     SHOW_LIB_VERSION(swscale,    SWSCALE);
1999     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
2000     SHOW_LIB_VERSION(postproc,   POSTPROC);
2001     writer_print_chapter_footer(w, "library_versions");
2002 }
2003
2004 static int opt_format(const char *opt, const char *arg)
2005 {
2006     iformat = av_find_input_format(arg);
2007     if (!iformat) {
2008         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
2009         return AVERROR(EINVAL);
2010     }
2011     return 0;
2012 }
2013
2014 static int opt_show_format_entry(const char *opt, const char *arg)
2015 {
2016     do_show_format = 1;
2017     av_dict_set(&fmt_entries_to_show, arg, "", 0);
2018     return 0;
2019 }
2020
2021 static void opt_input_file(void *optctx, const char *arg)
2022 {
2023     if (input_filename) {
2024         av_log(NULL, AV_LOG_ERROR,
2025                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
2026                 arg, input_filename);
2027         exit(1);
2028     }
2029     if (!strcmp(arg, "-"))
2030         arg = "pipe:";
2031     input_filename = arg;
2032 }
2033
2034 static int opt_help(const char *opt, const char *arg)
2035 {
2036     av_log_set_callback(log_callback_help);
2037     show_usage();
2038     show_help_options(options, "Main options:\n", 0, 0);
2039     printf("\n");
2040
2041     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
2042
2043     return 0;
2044 }
2045
2046 static int opt_pretty(const char *opt, const char *arg)
2047 {
2048     show_value_unit              = 1;
2049     use_value_prefix             = 1;
2050     use_byte_value_binary_prefix = 1;
2051     use_value_sexagesimal_format = 1;
2052     return 0;
2053 }
2054
2055 static int opt_show_versions(const char *opt, const char *arg)
2056 {
2057     do_show_program_version  = 1;
2058     do_show_library_versions = 1;
2059     return 0;
2060 }
2061
2062 static const OptionDef options[] = {
2063 #include "cmdutils_common_opts.h"
2064     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
2065     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
2066     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
2067     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
2068       "use binary prefixes for byte units" },
2069     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
2070       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
2071     { "pretty", 0, {(void*)&opt_pretty},
2072       "prettify the format of displayed values, make it more human readable" },
2073     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
2074       "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
2075     { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
2076     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
2077     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
2078     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
2079     { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
2080       "show a particular entry from the format/container info", "entry" },
2081     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
2082     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
2083     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
2084     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
2085     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
2086     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
2087     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
2088     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
2089     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
2090     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
2091     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
2092     { NULL, },
2093 };
2094
2095 int main(int argc, char **argv)
2096 {
2097     const Writer *w;
2098     WriterContext *wctx;
2099     char *buf;
2100     char *w_name = NULL, *w_args = NULL;
2101     int ret;
2102
2103     av_log_set_flags(AV_LOG_SKIP_REPEATED);
2104     parse_loglevel(argc, argv, options);
2105     av_register_all();
2106     avformat_network_init();
2107     init_opts();
2108 #if CONFIG_AVDEVICE
2109     avdevice_register_all();
2110 #endif
2111
2112     show_banner(argc, argv, options);
2113     parse_options(NULL, argc, argv, options, opt_input_file);
2114
2115     writer_register_all();
2116
2117     if (!print_format)
2118         print_format = av_strdup("default");
2119     w_name = av_strtok(print_format, "=", &buf);
2120     w_args = buf;
2121
2122     w = writer_get_by_name(w_name);
2123     if (!w) {
2124         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
2125         ret = AVERROR(EINVAL);
2126         goto end;
2127     }
2128
2129     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
2130         writer_print_header(wctx);
2131
2132         if (do_show_program_version)
2133             ffprobe_show_program_version(wctx);
2134         if (do_show_library_versions)
2135             ffprobe_show_library_versions(wctx);
2136
2137         if (!input_filename &&
2138             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
2139              (!do_show_program_version && !do_show_library_versions))) {
2140             show_usage();
2141             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
2142             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
2143             ret = AVERROR(EINVAL);
2144         } else if (input_filename) {
2145             ret = probe_file(wctx, input_filename);
2146             if (ret < 0 && do_show_error)
2147                 show_error(wctx, ret);
2148         }
2149
2150         writer_print_footer(wctx);
2151         writer_close(&wctx);
2152     }
2153
2154 end:
2155     av_freep(&print_format);
2156
2157     uninit_opts();
2158     av_dict_free(&fmt_entries_to_show);
2159
2160     avformat_network_deinit();
2161
2162     return ret;
2163 }