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