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