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