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