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