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