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