]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
vp9: add fate sample for parallelmode.
[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 "libavutil/ffversion.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/parseutils.h"
41 #include "libavutil/timecode.h"
42 #include "libavutil/timestamp.h"
43 #include "libavdevice/avdevice.h"
44 #include "libswscale/swscale.h"
45 #include "libswresample/swresample.h"
46 #include "libpostproc/postprocess.h"
47 #include "cmdutils.h"
48
49 const char program_name[] = "ffprobe";
50 const int program_birth_year = 2007;
51
52 static int do_bitexact = 0;
53 static int do_count_frames = 0;
54 static int do_count_packets = 0;
55 static int do_read_frames  = 0;
56 static int do_read_packets = 0;
57 static int do_show_chapters = 0;
58 static int do_show_error   = 0;
59 static int do_show_format  = 0;
60 static int do_show_frames  = 0;
61 static int do_show_packets = 0;
62 static int do_show_programs = 0;
63 static int do_show_streams = 0;
64 static int do_show_stream_disposition = 0;
65 static int do_show_data    = 0;
66 static int do_show_program_version  = 0;
67 static int do_show_library_versions = 0;
68
69 static int show_value_unit              = 0;
70 static int use_value_prefix             = 0;
71 static int use_byte_value_binary_prefix = 0;
72 static int use_value_sexagesimal_format = 0;
73 static int show_private_data            = 1;
74
75 static char *print_format;
76 static char *stream_specifier;
77
78 typedef struct {
79     int id;             ///< identifier
80     int64_t start, end; ///< start, end in second/AV_TIME_BASE units
81     int has_start, has_end;
82     int start_is_offset, end_is_offset;
83     int duration_frames;
84 } ReadInterval;
85
86 static ReadInterval *read_intervals;
87 static int read_intervals_nb = 0;
88
89 /* section structure definition */
90
91 #define SECTION_MAX_NB_CHILDREN 10
92
93 struct section {
94     int id;             ///< unique id identifying a section
95     const char *name;
96
97 #define SECTION_FLAG_IS_WRAPPER      1 ///< the section only contains other sections, but has no data at its own level
98 #define SECTION_FLAG_IS_ARRAY        2 ///< the section contains an array of elements of the same type
99 #define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
100                                            ///  For these sections the element_name field is mandatory.
101     int flags;
102     int children_ids[SECTION_MAX_NB_CHILDREN+1]; ///< list of children section IDS, terminated by -1
103     const char *element_name; ///< name of the contained element, if provided
104     const char *unique_name;  ///< unique section name, in case the name is ambiguous
105     AVDictionary *entries_to_show;
106     int show_all_entries;
107 };
108
109 typedef enum {
110     SECTION_ID_NONE = -1,
111     SECTION_ID_CHAPTER,
112     SECTION_ID_CHAPTER_TAGS,
113     SECTION_ID_CHAPTERS,
114     SECTION_ID_ERROR,
115     SECTION_ID_FORMAT,
116     SECTION_ID_FORMAT_TAGS,
117     SECTION_ID_FRAME,
118     SECTION_ID_FRAMES,
119     SECTION_ID_FRAME_TAGS,
120     SECTION_ID_LIBRARY_VERSION,
121     SECTION_ID_LIBRARY_VERSIONS,
122     SECTION_ID_PACKET,
123     SECTION_ID_PACKETS,
124     SECTION_ID_PACKETS_AND_FRAMES,
125     SECTION_ID_PROGRAM_STREAM_DISPOSITION,
126     SECTION_ID_PROGRAM_STREAM_TAGS,
127     SECTION_ID_PROGRAM,
128     SECTION_ID_PROGRAM_STREAMS,
129     SECTION_ID_PROGRAM_STREAM,
130     SECTION_ID_PROGRAM_TAGS,
131     SECTION_ID_PROGRAM_VERSION,
132     SECTION_ID_PROGRAMS,
133     SECTION_ID_ROOT,
134     SECTION_ID_STREAM,
135     SECTION_ID_STREAM_DISPOSITION,
136     SECTION_ID_STREAMS,
137     SECTION_ID_STREAM_TAGS,
138     SECTION_ID_SUBTITLE,
139 } SectionID;
140
141 static struct section sections[] = {
142     [SECTION_ID_CHAPTERS] =           { SECTION_ID_CHAPTERS, "chapters", SECTION_FLAG_IS_ARRAY, { SECTION_ID_CHAPTER, -1 } },
143     [SECTION_ID_CHAPTER] =            { SECTION_ID_CHAPTER, "chapter", 0, { SECTION_ID_CHAPTER_TAGS, -1 } },
144     [SECTION_ID_CHAPTER_TAGS] =       { SECTION_ID_CHAPTER_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "chapter_tags" },
145     [SECTION_ID_ERROR] =              { SECTION_ID_ERROR, "error", 0, { -1 } },
146     [SECTION_ID_FORMAT] =             { SECTION_ID_FORMAT, "format", 0, { SECTION_ID_FORMAT_TAGS, -1 } },
147     [SECTION_ID_FORMAT_TAGS] =        { SECTION_ID_FORMAT_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "format_tags" },
148     [SECTION_ID_FRAMES] =             { SECTION_ID_FRAMES, "frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME, SECTION_ID_SUBTITLE, -1 } },
149     [SECTION_ID_FRAME] =              { SECTION_ID_FRAME, "frame", 0, { SECTION_ID_FRAME_TAGS, -1 } },
150     [SECTION_ID_FRAME_TAGS] =         { SECTION_ID_FRAME_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "frame_tags" },
151     [SECTION_ID_LIBRARY_VERSIONS] =   { SECTION_ID_LIBRARY_VERSIONS, "library_versions", SECTION_FLAG_IS_ARRAY, { SECTION_ID_LIBRARY_VERSION, -1 } },
152     [SECTION_ID_LIBRARY_VERSION] =    { SECTION_ID_LIBRARY_VERSION, "library_version", 0, { -1 } },
153     [SECTION_ID_PACKETS] =            { SECTION_ID_PACKETS, "packets", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
154     [SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
155     [SECTION_ID_PACKET] =             { SECTION_ID_PACKET, "packet", 0, { -1 } },
156     [SECTION_ID_PROGRAM_STREAM_DISPOSITION] = { SECTION_ID_PROGRAM_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "program_stream_disposition" },
157     [SECTION_ID_PROGRAM_STREAM_TAGS] =        { SECTION_ID_PROGRAM_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_stream_tags" },
158     [SECTION_ID_PROGRAM] =                    { SECTION_ID_PROGRAM, "program", 0, { SECTION_ID_PROGRAM_TAGS, SECTION_ID_PROGRAM_STREAMS, -1 } },
159     [SECTION_ID_PROGRAM_STREAMS] =            { SECTION_ID_PROGRAM_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM_STREAM, -1 }, .unique_name = "program_streams" },
160     [SECTION_ID_PROGRAM_STREAM] =             { SECTION_ID_PROGRAM_STREAM, "stream", 0, { SECTION_ID_PROGRAM_STREAM_DISPOSITION, SECTION_ID_PROGRAM_STREAM_TAGS, -1 }, .unique_name = "program_stream" },
161     [SECTION_ID_PROGRAM_TAGS] =               { SECTION_ID_PROGRAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_tags" },
162     [SECTION_ID_PROGRAM_VERSION] =    { SECTION_ID_PROGRAM_VERSION, "program_version", 0, { -1 } },
163     [SECTION_ID_PROGRAMS] =                   { SECTION_ID_PROGRAMS, "programs", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM, -1 } },
164     [SECTION_ID_ROOT] =               { SECTION_ID_ROOT, "root", SECTION_FLAG_IS_WRAPPER,
165                                         { SECTION_ID_CHAPTERS, SECTION_ID_FORMAT, SECTION_ID_FRAMES, SECTION_ID_PROGRAMS, SECTION_ID_STREAMS,
166                                           SECTION_ID_PACKETS, SECTION_ID_ERROR, SECTION_ID_PROGRAM_VERSION, SECTION_ID_LIBRARY_VERSIONS, -1} },
167     [SECTION_ID_STREAMS] =            { SECTION_ID_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM, -1 } },
168     [SECTION_ID_STREAM] =             { SECTION_ID_STREAM, "stream", 0, { SECTION_ID_STREAM_DISPOSITION, SECTION_ID_STREAM_TAGS, -1 } },
169     [SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "stream_disposition" },
170     [SECTION_ID_STREAM_TAGS] =        { SECTION_ID_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "stream_tags" },
171     [SECTION_ID_SUBTITLE] =           { SECTION_ID_SUBTITLE, "subtitle", 0, { -1 } },
172 };
173
174 static const OptionDef *options;
175
176 /* FFprobe context */
177 static const char *input_filename;
178 static AVInputFormat *iformat = NULL;
179
180 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
181 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
182
183 static const char unit_second_str[]         = "s"    ;
184 static const char unit_hertz_str[]          = "Hz"   ;
185 static const char unit_byte_str[]           = "byte" ;
186 static const char unit_bit_per_second_str[] = "bit/s";
187
188 static uint64_t *nb_streams_packets;
189 static uint64_t *nb_streams_frames;
190 static int *selected_streams;
191
192 static void ffprobe_cleanup(int ret)
193 {
194     int i;
195     for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
196         av_dict_free(&(sections[i].entries_to_show));
197 }
198
199 struct unit_value {
200     union { double d; long long int i; } val;
201     const char *unit;
202 };
203
204 static char *value_string(char *buf, int buf_size, struct unit_value uv)
205 {
206     double vald;
207     long long int vali;
208     int show_float = 0;
209
210     if (uv.unit == unit_second_str) {
211         vald = uv.val.d;
212         show_float = 1;
213     } else {
214         vald = vali = uv.val.i;
215     }
216
217     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
218         double secs;
219         int hours, mins;
220         secs  = vald;
221         mins  = (int)secs / 60;
222         secs  = secs - mins * 60;
223         hours = mins / 60;
224         mins %= 60;
225         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
226     } else {
227         const char *prefix_string = "";
228
229         if (use_value_prefix && vald > 1) {
230             long long int index;
231
232             if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
233                 index = (long long int) (log2(vald)) / 10;
234                 index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
235                 vald /= exp2(index * 10);
236                 prefix_string = binary_unit_prefixes[index];
237             } else {
238                 index = (long long int) (log10(vald)) / 3;
239                 index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
240                 vald /= pow(10, index * 3);
241                 prefix_string = decimal_unit_prefixes[index];
242             }
243         }
244
245         if (show_float || (use_value_prefix && vald != (long long int)vald))
246             snprintf(buf, buf_size, "%f", vald);
247         else
248             snprintf(buf, buf_size, "%lld", vali);
249         av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
250                  prefix_string, show_value_unit ? uv.unit : "");
251     }
252
253     return buf;
254 }
255
256 /* WRITERS API */
257
258 typedef struct WriterContext WriterContext;
259
260 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
261 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
262
263 typedef enum {
264     WRITER_STRING_VALIDATION_FAIL,
265     WRITER_STRING_VALIDATION_REPLACE,
266     WRITER_STRING_VALIDATION_IGNORE,
267     WRITER_STRING_VALIDATION_NB
268 } StringValidation;
269
270 typedef struct Writer {
271     const AVClass *priv_class;      ///< private class of the writer, if any
272     int priv_size;                  ///< private size for the writer context
273     const char *name;
274
275     int  (*init)  (WriterContext *wctx);
276     void (*uninit)(WriterContext *wctx);
277
278     void (*print_section_header)(WriterContext *wctx);
279     void (*print_section_footer)(WriterContext *wctx);
280     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
281     void (*print_rational)      (WriterContext *wctx, AVRational *q, char *sep);
282     void (*print_string)        (WriterContext *wctx, const char *, const char *);
283     int flags;                  ///< a combination or WRITER_FLAG_*
284 } Writer;
285
286 #define SECTION_MAX_NB_LEVELS 10
287
288 struct WriterContext {
289     const AVClass *class;           ///< class of the writer
290     const Writer *writer;           ///< the Writer of which this is an instance
291     char *name;                     ///< name of this writer instance
292     void *priv;                     ///< private data for use by the filter
293
294     const struct section *sections; ///< array containing all sections
295     int nb_sections;                ///< number of sections
296
297     int level;                      ///< current level, starting from 0
298
299     /** number of the item printed in the given section, starting from 0 */
300     unsigned int nb_item[SECTION_MAX_NB_LEVELS];
301
302     /** section per each level */
303     const struct section *section[SECTION_MAX_NB_LEVELS];
304     AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
305                                                   ///  used by various writers
306
307     unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
308     unsigned int nb_section_frame;  ///< number of the frame  section in case we are in "packets_and_frames" section
309     unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
310
311     StringValidation string_validation;
312     char *string_validation_replacement;
313     unsigned int string_validation_utf8_flags;
314 };
315
316 static const char *writer_get_name(void *p)
317 {
318     WriterContext *wctx = p;
319     return wctx->writer->name;
320 }
321
322 #define OFFSET(x) offsetof(WriterContext, x)
323
324 static const AVOption writer_options[] = {
325     { "string_validation", "set string validation mode",
326       OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
327     { "sv", "set string validation mode",
328       OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
329     { "ignore",  NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_IGNORE},  .unit = "sv" },
330     { "replace", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_REPLACE}, .unit = "sv" },
331     { "fail",    NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_FAIL},    .unit = "sv" },
332     { "string_validation_replacement", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
333     { "svr", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
334     { NULL }
335 };
336
337 static void *writer_child_next(void *obj, void *prev)
338 {
339     WriterContext *ctx = obj;
340     if (!prev && ctx->writer && ctx->writer->priv_class && ctx->priv)
341         return ctx->priv;
342     return NULL;
343 }
344
345 static const AVClass writer_class = {
346     .class_name = "Writer",
347     .item_name  = writer_get_name,
348     .option     = writer_options,
349     .version    = LIBAVUTIL_VERSION_INT,
350     .child_next = writer_child_next,
351 };
352
353 static void writer_close(WriterContext **wctx)
354 {
355     int i;
356
357     if (!*wctx)
358         return;
359
360     if ((*wctx)->writer->uninit)
361         (*wctx)->writer->uninit(*wctx);
362     for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
363         av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
364     if ((*wctx)->writer->priv_class)
365         av_opt_free((*wctx)->priv);
366     av_freep(&((*wctx)->priv));
367     av_freep(wctx);
368 }
369
370 static void bprint_bytes(AVBPrint *bp, const uint8_t *ubuf, size_t ubuf_size)
371 {
372     int i;
373     av_bprintf(bp, "0X");
374     for (i = 0; i < ubuf_size; i++)
375         av_bprintf(bp, "%02X", ubuf[i]);
376 }
377
378
379 static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
380                        const struct section *sections, int nb_sections)
381 {
382     int i, ret = 0;
383
384     if (!(*wctx = av_mallocz(sizeof(WriterContext)))) {
385         ret = AVERROR(ENOMEM);
386         goto fail;
387     }
388
389     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
390         ret = AVERROR(ENOMEM);
391         goto fail;
392     }
393
394     (*wctx)->class = &writer_class;
395     (*wctx)->writer = writer;
396     (*wctx)->level = -1;
397     (*wctx)->sections = sections;
398     (*wctx)->nb_sections = nb_sections;
399
400     av_opt_set_defaults(*wctx);
401
402     if (writer->priv_class) {
403         void *priv_ctx = (*wctx)->priv;
404         *((const AVClass **)priv_ctx) = writer->priv_class;
405         av_opt_set_defaults(priv_ctx);
406     }
407
408     /* convert options to dictionary */
409     if (args) {
410         AVDictionary *opts = NULL;
411         AVDictionaryEntry *opt = NULL;
412
413         if ((ret = av_dict_parse_string(&opts, args, "=", ":", 0)) < 0) {
414             av_log(*wctx, AV_LOG_ERROR, "Failed to parse option string '%s' provided to writer context\n", args);
415             av_dict_free(&opts);
416             goto fail;
417         }
418
419         while ((opt = av_dict_get(opts, "", opt, AV_DICT_IGNORE_SUFFIX))) {
420             if ((ret = av_opt_set(*wctx, opt->key, opt->value, AV_OPT_SEARCH_CHILDREN)) < 0) {
421                 av_log(*wctx, AV_LOG_ERROR, "Failed to set option '%s' with value '%s' provided to writer context\n",
422                        opt->key, opt->value);
423                 av_dict_free(&opts);
424                 goto fail;
425             }
426         }
427
428         av_dict_free(&opts);
429     }
430
431     /* validate replace string */
432     {
433         const uint8_t *p = (*wctx)->string_validation_replacement;
434         const uint8_t *endp = p + strlen(p);
435         while (*p) {
436             const uint8_t *p0 = p;
437             int32_t code;
438             ret = av_utf8_decode(&code, &p, endp, (*wctx)->string_validation_utf8_flags);
439             if (ret < 0) {
440                 AVBPrint bp;
441                 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
442                 bprint_bytes(&bp, p0, p-p0),
443                     av_log(wctx, AV_LOG_ERROR,
444                            "Invalid UTF8 sequence %s found in string validation replace '%s'\n",
445                            bp.str, (*wctx)->string_validation_replacement);
446                 return ret;
447             }
448         }
449     }
450
451     for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
452         av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
453
454     if ((*wctx)->writer->init)
455         ret = (*wctx)->writer->init(*wctx);
456     if (ret < 0)
457         goto fail;
458
459     return 0;
460
461 fail:
462     writer_close(wctx);
463     return ret;
464 }
465
466 static inline void writer_print_section_header(WriterContext *wctx,
467                                                int section_id)
468 {
469     int parent_section_id;
470     wctx->level++;
471     av_assert0(wctx->level < SECTION_MAX_NB_LEVELS);
472     parent_section_id = wctx->level ?
473         (wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
474
475     wctx->nb_item[wctx->level] = 0;
476     wctx->section[wctx->level] = &wctx->sections[section_id];
477
478     if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
479         wctx->nb_section_packet = wctx->nb_section_frame =
480         wctx->nb_section_packet_frame = 0;
481     } else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
482         wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
483             wctx->nb_section_packet : wctx->nb_section_frame;
484     }
485
486     if (wctx->writer->print_section_header)
487         wctx->writer->print_section_header(wctx);
488 }
489
490 static inline void writer_print_section_footer(WriterContext *wctx)
491 {
492     int section_id = wctx->section[wctx->level]->id;
493     int parent_section_id = wctx->level ?
494         wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
495
496     if (parent_section_id != SECTION_ID_NONE)
497         wctx->nb_item[wctx->level-1]++;
498     if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
499         if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
500         else                                     wctx->nb_section_frame++;
501     }
502     if (wctx->writer->print_section_footer)
503         wctx->writer->print_section_footer(wctx);
504     wctx->level--;
505 }
506
507 static inline void writer_print_integer(WriterContext *wctx,
508                                         const char *key, long long int val)
509 {
510     const struct section *section = wctx->section[wctx->level];
511
512     if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
513         wctx->writer->print_integer(wctx, key, val);
514         wctx->nb_item[wctx->level]++;
515     }
516 }
517
518 static inline int validate_string(WriterContext *wctx, char **dstp, const char *src)
519 {
520     const uint8_t *p, *endp;
521     AVBPrint dstbuf;
522     int invalid_chars_nb = 0, ret = 0;
523
524     av_bprint_init(&dstbuf, 0, AV_BPRINT_SIZE_UNLIMITED);
525
526     endp = src + strlen(src);
527     for (p = (uint8_t *)src; *p;) {
528         uint32_t code;
529         int invalid = 0;
530         const uint8_t *p0 = p;
531
532         if (av_utf8_decode(&code, &p, endp, wctx->string_validation_utf8_flags) < 0) {
533             AVBPrint bp;
534             av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
535             bprint_bytes(&bp, p0, p-p0);
536             av_log(wctx, AV_LOG_DEBUG,
537                    "Invalid UTF-8 sequence %s found in string '%s'\n", bp.str, src);
538             invalid = 1;
539         }
540
541         if (invalid) {
542             invalid_chars_nb++;
543
544             switch (wctx->string_validation) {
545             case WRITER_STRING_VALIDATION_FAIL:
546                 av_log(wctx, AV_LOG_ERROR,
547                        "Invalid UTF-8 sequence found in string '%s'\n", src);
548                 ret = AVERROR_INVALIDDATA;
549                 goto end;
550                 break;
551
552             case WRITER_STRING_VALIDATION_REPLACE:
553                 av_bprintf(&dstbuf, "%s", wctx->string_validation_replacement);
554                 break;
555             }
556         }
557
558         if (!invalid || wctx->string_validation == WRITER_STRING_VALIDATION_IGNORE)
559             av_bprint_append_data(&dstbuf, p0, p-p0);
560     }
561
562     if (invalid_chars_nb && wctx->string_validation == WRITER_STRING_VALIDATION_REPLACE) {
563         av_log(wctx, AV_LOG_WARNING,
564                "%d invalid UTF-8 sequence(s) found in string '%s', replaced with '%s'\n",
565                invalid_chars_nb, src, wctx->string_validation_replacement);
566     }
567
568 end:
569     av_bprint_finalize(&dstbuf, dstp);
570     return ret;
571 }
572
573 #define PRINT_STRING_OPT      1
574 #define PRINT_STRING_VALIDATE 2
575
576 static inline int writer_print_string(WriterContext *wctx,
577                                       const char *key, const char *val, int flags)
578 {
579     const struct section *section = wctx->section[wctx->level];
580     int ret = 0;
581
582     if ((flags & PRINT_STRING_OPT)
583         && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
584         return 0;
585
586     if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
587         if (flags & PRINT_STRING_VALIDATE) {
588             char *key1 = NULL, *val1 = NULL;
589             ret = validate_string(wctx, &key1, key);
590             if (ret < 0) goto end;
591             ret = validate_string(wctx, &val1, val);
592             if (ret < 0) goto end;
593             wctx->writer->print_string(wctx, key1, val1);
594         end:
595             if (ret < 0) {
596                 av_log(wctx, AV_LOG_ERROR,
597                        "Invalid key=value string combination %s=%s in section %s\n",
598                        key, val, section->unique_name);
599             }
600             av_free(key1);
601             av_free(val1);
602         } else {
603             wctx->writer->print_string(wctx, key, val);
604         }
605
606         wctx->nb_item[wctx->level]++;
607     }
608
609     return ret;
610 }
611
612 static inline void writer_print_rational(WriterContext *wctx,
613                                          const char *key, AVRational q, char sep)
614 {
615     AVBPrint buf;
616     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
617     av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
618     writer_print_string(wctx, key, buf.str, 0);
619 }
620
621 static void writer_print_time(WriterContext *wctx, const char *key,
622                               int64_t ts, const AVRational *time_base, int is_duration)
623 {
624     char buf[128];
625
626     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
627         writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
628     } else {
629         double d = ts * av_q2d(*time_base);
630         struct unit_value uv;
631         uv.val.d = d;
632         uv.unit = unit_second_str;
633         value_string(buf, sizeof(buf), uv);
634         writer_print_string(wctx, key, buf, 0);
635     }
636 }
637
638 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
639 {
640     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
641         writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
642     } else {
643         writer_print_integer(wctx, key, ts);
644     }
645 }
646
647 static void writer_print_data(WriterContext *wctx, const char *name,
648                               uint8_t *data, int size)
649 {
650     AVBPrint bp;
651     int offset = 0, l, i;
652
653     av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
654     av_bprintf(&bp, "\n");
655     while (size) {
656         av_bprintf(&bp, "%08x: ", offset);
657         l = FFMIN(size, 16);
658         for (i = 0; i < l; i++) {
659             av_bprintf(&bp, "%02x", data[i]);
660             if (i & 1)
661                 av_bprintf(&bp, " ");
662         }
663         av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
664         for (i = 0; i < l; i++)
665             av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
666         av_bprintf(&bp, "\n");
667         offset += l;
668         data   += l;
669         size   -= l;
670     }
671     writer_print_string(wctx, name, bp.str, 0);
672     av_bprint_finalize(&bp, NULL);
673 }
674
675 #define MAX_REGISTERED_WRITERS_NB 64
676
677 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
678
679 static int writer_register(const Writer *writer)
680 {
681     static int next_registered_writer_idx = 0;
682
683     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
684         return AVERROR(ENOMEM);
685
686     registered_writers[next_registered_writer_idx++] = writer;
687     return 0;
688 }
689
690 static const Writer *writer_get_by_name(const char *name)
691 {
692     int i;
693
694     for (i = 0; registered_writers[i]; i++)
695         if (!strcmp(registered_writers[i]->name, name))
696             return registered_writers[i];
697
698     return NULL;
699 }
700
701
702 /* WRITERS */
703
704 #define DEFINE_WRITER_CLASS(name)                   \
705 static const char *name##_get_name(void *ctx)       \
706 {                                                   \
707     return #name ;                                  \
708 }                                                   \
709 static const AVClass name##_class = {               \
710     .class_name = #name,                            \
711     .item_name  = name##_get_name,                  \
712     .option     = name##_options                    \
713 }
714
715 /* Default output */
716
717 typedef struct DefaultContext {
718     const AVClass *class;
719     int nokey;
720     int noprint_wrappers;
721     int nested_section[SECTION_MAX_NB_LEVELS];
722 } DefaultContext;
723
724 #undef OFFSET
725 #define OFFSET(x) offsetof(DefaultContext, x)
726
727 static const AVOption default_options[] = {
728     { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
729     { "nw",               "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
730     { "nokey",          "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
731     { "nk",             "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
732     {NULL},
733 };
734
735 DEFINE_WRITER_CLASS(default);
736
737 /* lame uppercasing routine, assumes the string is lower case ASCII */
738 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
739 {
740     int i;
741     for (i = 0; src[i] && i < dst_size-1; i++)
742         dst[i] = av_toupper(src[i]);
743     dst[i] = 0;
744     return dst;
745 }
746
747 static void default_print_section_header(WriterContext *wctx)
748 {
749     DefaultContext *def = wctx->priv;
750     char buf[32];
751     const struct section *section = wctx->section[wctx->level];
752     const struct section *parent_section = wctx->level ?
753         wctx->section[wctx->level-1] : NULL;
754
755     av_bprint_clear(&wctx->section_pbuf[wctx->level]);
756     if (parent_section &&
757         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
758         def->nested_section[wctx->level] = 1;
759         av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
760                    wctx->section_pbuf[wctx->level-1].str,
761                    upcase_string(buf, sizeof(buf),
762                                  av_x_if_null(section->element_name, section->name)));
763     }
764
765     if (def->noprint_wrappers || def->nested_section[wctx->level])
766         return;
767
768     if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
769         printf("[%s]\n", upcase_string(buf, sizeof(buf), section->name));
770 }
771
772 static void default_print_section_footer(WriterContext *wctx)
773 {
774     DefaultContext *def = wctx->priv;
775     const struct section *section = wctx->section[wctx->level];
776     char buf[32];
777
778     if (def->noprint_wrappers || def->nested_section[wctx->level])
779         return;
780
781     if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
782         printf("[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
783 }
784
785 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
786 {
787     DefaultContext *def = wctx->priv;
788
789     if (!def->nokey)
790         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
791     printf("%s\n", value);
792 }
793
794 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
795 {
796     DefaultContext *def = wctx->priv;
797
798     if (!def->nokey)
799         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
800     printf("%lld\n", value);
801 }
802
803 static const Writer default_writer = {
804     .name                  = "default",
805     .priv_size             = sizeof(DefaultContext),
806     .print_section_header  = default_print_section_header,
807     .print_section_footer  = default_print_section_footer,
808     .print_integer         = default_print_int,
809     .print_string          = default_print_str,
810     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
811     .priv_class            = &default_class,
812 };
813
814 /* Compact output */
815
816 /**
817  * Apply C-language-like string escaping.
818  */
819 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
820 {
821     const char *p;
822
823     for (p = src; *p; p++) {
824         switch (*p) {
825         case '\b': av_bprintf(dst, "%s", "\\b");  break;
826         case '\f': av_bprintf(dst, "%s", "\\f");  break;
827         case '\n': av_bprintf(dst, "%s", "\\n");  break;
828         case '\r': av_bprintf(dst, "%s", "\\r");  break;
829         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
830         default:
831             if (*p == sep)
832                 av_bprint_chars(dst, '\\', 1);
833             av_bprint_chars(dst, *p, 1);
834         }
835     }
836     return dst->str;
837 }
838
839 /**
840  * Quote fields containing special characters, check RFC4180.
841  */
842 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
843 {
844     char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
845     int needs_quoting = !!src[strcspn(src, meta_chars)];
846
847     if (needs_quoting)
848         av_bprint_chars(dst, '"', 1);
849
850     for (; *src; src++) {
851         if (*src == '"')
852             av_bprint_chars(dst, '"', 1);
853         av_bprint_chars(dst, *src, 1);
854     }
855     if (needs_quoting)
856         av_bprint_chars(dst, '"', 1);
857     return dst->str;
858 }
859
860 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
861 {
862     return src;
863 }
864
865 typedef struct CompactContext {
866     const AVClass *class;
867     char *item_sep_str;
868     char item_sep;
869     int nokey;
870     int print_section;
871     char *escape_mode_str;
872     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
873     int nested_section[SECTION_MAX_NB_LEVELS];
874     int has_nested_elems[SECTION_MAX_NB_LEVELS];
875     int terminate_line[SECTION_MAX_NB_LEVELS];
876 } CompactContext;
877
878 #undef OFFSET
879 #define OFFSET(x) offsetof(CompactContext, x)
880
881 static const AVOption compact_options[]= {
882     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
883     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
884     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
885     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
886     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
887     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
888     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
889     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
890     {NULL},
891 };
892
893 DEFINE_WRITER_CLASS(compact);
894
895 static av_cold int compact_init(WriterContext *wctx)
896 {
897     CompactContext *compact = wctx->priv;
898
899     if (strlen(compact->item_sep_str) != 1) {
900         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
901                compact->item_sep_str);
902         return AVERROR(EINVAL);
903     }
904     compact->item_sep = compact->item_sep_str[0];
905
906     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
907     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
908     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
909     else {
910         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
911         return AVERROR(EINVAL);
912     }
913
914     return 0;
915 }
916
917 static void compact_print_section_header(WriterContext *wctx)
918 {
919     CompactContext *compact = wctx->priv;
920     const struct section *section = wctx->section[wctx->level];
921     const struct section *parent_section = wctx->level ?
922         wctx->section[wctx->level-1] : NULL;
923     compact->terminate_line[wctx->level] = 1;
924     compact->has_nested_elems[wctx->level] = 0;
925
926     av_bprint_clear(&wctx->section_pbuf[wctx->level]);
927     if (!(section->flags & SECTION_FLAG_IS_ARRAY) && parent_section &&
928         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
929         compact->nested_section[wctx->level] = 1;
930         compact->has_nested_elems[wctx->level-1] = 1;
931         av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
932                    wctx->section_pbuf[wctx->level-1].str,
933                    (char *)av_x_if_null(section->element_name, section->name));
934         wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
935     } else {
936         if (parent_section && compact->has_nested_elems[wctx->level-1] &&
937             (section->flags & SECTION_FLAG_IS_ARRAY)) {
938             compact->terminate_line[wctx->level-1] = 0;
939             printf("\n");
940         }
941         if (compact->print_section &&
942             !(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
943             printf("%s%c", section->name, compact->item_sep);
944     }
945 }
946
947 static void compact_print_section_footer(WriterContext *wctx)
948 {
949     CompactContext *compact = wctx->priv;
950
951     if (!compact->nested_section[wctx->level] &&
952         compact->terminate_line[wctx->level] &&
953         !(wctx->section[wctx->level]->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
954         printf("\n");
955 }
956
957 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
958 {
959     CompactContext *compact = wctx->priv;
960     AVBPrint buf;
961
962     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
963     if (!compact->nokey)
964         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
965     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
966     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
967     av_bprint_finalize(&buf, NULL);
968 }
969
970 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
971 {
972     CompactContext *compact = wctx->priv;
973
974     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
975     if (!compact->nokey)
976         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
977     printf("%lld", value);
978 }
979
980 static const Writer compact_writer = {
981     .name                 = "compact",
982     .priv_size            = sizeof(CompactContext),
983     .init                 = compact_init,
984     .print_section_header = compact_print_section_header,
985     .print_section_footer = compact_print_section_footer,
986     .print_integer        = compact_print_int,
987     .print_string         = compact_print_str,
988     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
989     .priv_class           = &compact_class,
990 };
991
992 /* CSV output */
993
994 #undef OFFSET
995 #define OFFSET(x) offsetof(CompactContext, x)
996
997 static const AVOption csv_options[] = {
998     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
999     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
1000     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1001     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1002     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
1003     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
1004     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1005     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
1006     {NULL},
1007 };
1008
1009 DEFINE_WRITER_CLASS(csv);
1010
1011 static const Writer csv_writer = {
1012     .name                 = "csv",
1013     .priv_size            = sizeof(CompactContext),
1014     .init                 = compact_init,
1015     .print_section_header = compact_print_section_header,
1016     .print_section_footer = compact_print_section_footer,
1017     .print_integer        = compact_print_int,
1018     .print_string         = compact_print_str,
1019     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
1020     .priv_class           = &csv_class,
1021 };
1022
1023 /* Flat output */
1024
1025 typedef struct FlatContext {
1026     const AVClass *class;
1027     const char *sep_str;
1028     char sep;
1029     int hierarchical;
1030 } FlatContext;
1031
1032 #undef OFFSET
1033 #define OFFSET(x) offsetof(FlatContext, x)
1034
1035 static const AVOption flat_options[]= {
1036     {"sep_char", "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
1037     {"s",        "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
1038     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1039     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1040     {NULL},
1041 };
1042
1043 DEFINE_WRITER_CLASS(flat);
1044
1045 static av_cold int flat_init(WriterContext *wctx)
1046 {
1047     FlatContext *flat = wctx->priv;
1048
1049     if (strlen(flat->sep_str) != 1) {
1050         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
1051                flat->sep_str);
1052         return AVERROR(EINVAL);
1053     }
1054     flat->sep = flat->sep_str[0];
1055
1056     return 0;
1057 }
1058
1059 static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
1060 {
1061     const char *p;
1062
1063     for (p = src; *p; p++) {
1064         if (!((*p >= '0' && *p <= '9') ||
1065               (*p >= 'a' && *p <= 'z') ||
1066               (*p >= 'A' && *p <= 'Z')))
1067             av_bprint_chars(dst, '_', 1);
1068         else
1069             av_bprint_chars(dst, *p, 1);
1070     }
1071     return dst->str;
1072 }
1073
1074 static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
1075 {
1076     const char *p;
1077
1078     for (p = src; *p; p++) {
1079         switch (*p) {
1080         case '\n': av_bprintf(dst, "%s", "\\n");  break;
1081         case '\r': av_bprintf(dst, "%s", "\\r");  break;
1082         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
1083         case '"':  av_bprintf(dst, "%s", "\\\""); break;
1084         case '`':  av_bprintf(dst, "%s", "\\`");  break;
1085         case '$':  av_bprintf(dst, "%s", "\\$");  break;
1086         default:   av_bprint_chars(dst, *p, 1);   break;
1087         }
1088     }
1089     return dst->str;
1090 }
1091
1092 static void flat_print_section_header(WriterContext *wctx)
1093 {
1094     FlatContext *flat = wctx->priv;
1095     AVBPrint *buf = &wctx->section_pbuf[wctx->level];
1096     const struct section *section = wctx->section[wctx->level];
1097     const struct section *parent_section = wctx->level ?
1098         wctx->section[wctx->level-1] : NULL;
1099
1100     /* build section header */
1101     av_bprint_clear(buf);
1102     if (!parent_section)
1103         return;
1104     av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
1105
1106     if (flat->hierarchical ||
1107         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
1108         av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
1109
1110         if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
1111             int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
1112                 wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
1113             av_bprintf(buf, "%d%s", n, flat->sep_str);
1114         }
1115     }
1116 }
1117
1118 static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
1119 {
1120     printf("%s%s=%lld\n", wctx->section_pbuf[wctx->level].str, key, value);
1121 }
1122
1123 static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
1124 {
1125     FlatContext *flat = wctx->priv;
1126     AVBPrint buf;
1127
1128     printf("%s", wctx->section_pbuf[wctx->level].str);
1129     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1130     printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
1131     av_bprint_clear(&buf);
1132     printf("\"%s\"\n", flat_escape_value_str(&buf, value));
1133     av_bprint_finalize(&buf, NULL);
1134 }
1135
1136 static const Writer flat_writer = {
1137     .name                  = "flat",
1138     .priv_size             = sizeof(FlatContext),
1139     .init                  = flat_init,
1140     .print_section_header  = flat_print_section_header,
1141     .print_integer         = flat_print_int,
1142     .print_string          = flat_print_str,
1143     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1144     .priv_class            = &flat_class,
1145 };
1146
1147 /* INI format output */
1148
1149 typedef struct {
1150     const AVClass *class;
1151     int hierarchical;
1152 } INIContext;
1153
1154 #undef OFFSET
1155 #define OFFSET(x) offsetof(INIContext, x)
1156
1157 static const AVOption ini_options[] = {
1158     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1159     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
1160     {NULL},
1161 };
1162
1163 DEFINE_WRITER_CLASS(ini);
1164
1165 static char *ini_escape_str(AVBPrint *dst, const char *src)
1166 {
1167     int i = 0;
1168     char c = 0;
1169
1170     while (c = src[i++]) {
1171         switch (c) {
1172         case '\b': av_bprintf(dst, "%s", "\\b"); break;
1173         case '\f': av_bprintf(dst, "%s", "\\f"); break;
1174         case '\n': av_bprintf(dst, "%s", "\\n"); break;
1175         case '\r': av_bprintf(dst, "%s", "\\r"); break;
1176         case '\t': av_bprintf(dst, "%s", "\\t"); break;
1177         case '\\':
1178         case '#' :
1179         case '=' :
1180         case ':' : av_bprint_chars(dst, '\\', 1);
1181         default:
1182             if ((unsigned char)c < 32)
1183                 av_bprintf(dst, "\\x00%02x", c & 0xff);
1184             else
1185                 av_bprint_chars(dst, c, 1);
1186             break;
1187         }
1188     }
1189     return dst->str;
1190 }
1191
1192 static void ini_print_section_header(WriterContext *wctx)
1193 {
1194     INIContext *ini = wctx->priv;
1195     AVBPrint *buf = &wctx->section_pbuf[wctx->level];
1196     const struct section *section = wctx->section[wctx->level];
1197     const struct section *parent_section = wctx->level ?
1198         wctx->section[wctx->level-1] : NULL;
1199
1200     av_bprint_clear(buf);
1201     if (!parent_section) {
1202         printf("# ffprobe output\n\n");
1203         return;
1204     }
1205
1206     if (wctx->nb_item[wctx->level-1])
1207         printf("\n");
1208
1209     av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
1210     if (ini->hierarchical ||
1211         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
1212         av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
1213
1214         if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
1215             int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
1216                 wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
1217             av_bprintf(buf, ".%d", n);
1218         }
1219     }
1220
1221     if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
1222         printf("[%s]\n", buf->str);
1223 }
1224
1225 static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
1226 {
1227     AVBPrint buf;
1228
1229     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1230     printf("%s=", ini_escape_str(&buf, key));
1231     av_bprint_clear(&buf);
1232     printf("%s\n", ini_escape_str(&buf, value));
1233     av_bprint_finalize(&buf, NULL);
1234 }
1235
1236 static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
1237 {
1238     printf("%s=%lld\n", key, value);
1239 }
1240
1241 static const Writer ini_writer = {
1242     .name                  = "ini",
1243     .priv_size             = sizeof(INIContext),
1244     .print_section_header  = ini_print_section_header,
1245     .print_integer         = ini_print_int,
1246     .print_string          = ini_print_str,
1247     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1248     .priv_class            = &ini_class,
1249 };
1250
1251 /* JSON output */
1252
1253 typedef struct {
1254     const AVClass *class;
1255     int indent_level;
1256     int compact;
1257     const char *item_sep, *item_start_end;
1258 } JSONContext;
1259
1260 #undef OFFSET
1261 #define OFFSET(x) offsetof(JSONContext, x)
1262
1263 static const AVOption json_options[]= {
1264     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1265     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1266     { NULL }
1267 };
1268
1269 DEFINE_WRITER_CLASS(json);
1270
1271 static av_cold int json_init(WriterContext *wctx)
1272 {
1273     JSONContext *json = wctx->priv;
1274
1275     json->item_sep       = json->compact ? ", " : ",\n";
1276     json->item_start_end = json->compact ? " "  : "\n";
1277
1278     return 0;
1279 }
1280
1281 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1282 {
1283     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
1284     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
1285     const char *p;
1286
1287     for (p = src; *p; p++) {
1288         char *s = strchr(json_escape, *p);
1289         if (s) {
1290             av_bprint_chars(dst, '\\', 1);
1291             av_bprint_chars(dst, json_subst[s - json_escape], 1);
1292         } else if ((unsigned char)*p < 32) {
1293             av_bprintf(dst, "\\u00%02x", *p & 0xff);
1294         } else {
1295             av_bprint_chars(dst, *p, 1);
1296         }
1297     }
1298     return dst->str;
1299 }
1300
1301 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
1302
1303 static void json_print_section_header(WriterContext *wctx)
1304 {
1305     JSONContext *json = wctx->priv;
1306     AVBPrint buf;
1307     const struct section *section = wctx->section[wctx->level];
1308     const struct section *parent_section = wctx->level ?
1309         wctx->section[wctx->level-1] : NULL;
1310
1311     if (wctx->level && wctx->nb_item[wctx->level-1])
1312         printf(",\n");
1313
1314     if (section->flags & SECTION_FLAG_IS_WRAPPER) {
1315         printf("{\n");
1316         json->indent_level++;
1317     } else {
1318         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1319         json_escape_str(&buf, section->name, wctx);
1320         JSON_INDENT();
1321
1322         json->indent_level++;
1323         if (section->flags & SECTION_FLAG_IS_ARRAY) {
1324             printf("\"%s\": [\n", buf.str);
1325         } else if (parent_section && !(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
1326             printf("\"%s\": {%s", buf.str, json->item_start_end);
1327         } else {
1328             printf("{%s", json->item_start_end);
1329
1330             /* this is required so the parser can distinguish between packets and frames */
1331             if (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
1332                 if (!json->compact)
1333                     JSON_INDENT();
1334                 printf("\"type\": \"%s\"%s", section->name, json->item_sep);
1335             }
1336         }
1337         av_bprint_finalize(&buf, NULL);
1338     }
1339 }
1340
1341 static void json_print_section_footer(WriterContext *wctx)
1342 {
1343     JSONContext *json = wctx->priv;
1344     const struct section *section = wctx->section[wctx->level];
1345
1346     if (wctx->level == 0) {
1347         json->indent_level--;
1348         printf("\n}\n");
1349     } else if (section->flags & SECTION_FLAG_IS_ARRAY) {
1350         printf("\n");
1351         json->indent_level--;
1352         JSON_INDENT();
1353         printf("]");
1354     } else {
1355         printf("%s", json->item_start_end);
1356         json->indent_level--;
1357         if (!json->compact)
1358             JSON_INDENT();
1359         printf("}");
1360     }
1361 }
1362
1363 static inline void json_print_item_str(WriterContext *wctx,
1364                                        const char *key, const char *value)
1365 {
1366     AVBPrint buf;
1367
1368     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1369     printf("\"%s\":", json_escape_str(&buf, key,   wctx));
1370     av_bprint_clear(&buf);
1371     printf(" \"%s\"", json_escape_str(&buf, value, wctx));
1372     av_bprint_finalize(&buf, NULL);
1373 }
1374
1375 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
1376 {
1377     JSONContext *json = wctx->priv;
1378
1379     if (wctx->nb_item[wctx->level])
1380         printf("%s", json->item_sep);
1381     if (!json->compact)
1382         JSON_INDENT();
1383     json_print_item_str(wctx, key, value);
1384 }
1385
1386 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
1387 {
1388     JSONContext *json = wctx->priv;
1389     AVBPrint buf;
1390
1391     if (wctx->nb_item[wctx->level])
1392         printf("%s", json->item_sep);
1393     if (!json->compact)
1394         JSON_INDENT();
1395
1396     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1397     printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
1398     av_bprint_finalize(&buf, NULL);
1399 }
1400
1401 static const Writer json_writer = {
1402     .name                 = "json",
1403     .priv_size            = sizeof(JSONContext),
1404     .init                 = json_init,
1405     .print_section_header = json_print_section_header,
1406     .print_section_footer = json_print_section_footer,
1407     .print_integer        = json_print_int,
1408     .print_string         = json_print_str,
1409     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1410     .priv_class           = &json_class,
1411 };
1412
1413 /* XML output */
1414
1415 typedef struct {
1416     const AVClass *class;
1417     int within_tag;
1418     int indent_level;
1419     int fully_qualified;
1420     int xsd_strict;
1421 } XMLContext;
1422
1423 #undef OFFSET
1424 #define OFFSET(x) offsetof(XMLContext, x)
1425
1426 static const AVOption xml_options[] = {
1427     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1428     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1429     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1430     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1431     {NULL},
1432 };
1433
1434 DEFINE_WRITER_CLASS(xml);
1435
1436 static av_cold int xml_init(WriterContext *wctx)
1437 {
1438     XMLContext *xml = wctx->priv;
1439
1440     if (xml->xsd_strict) {
1441         xml->fully_qualified = 1;
1442 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
1443         if (opt) {                                                      \
1444             av_log(wctx, AV_LOG_ERROR,                                  \
1445                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1446                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1447             return AVERROR(EINVAL);                                     \
1448         }
1449         CHECK_COMPLIANCE(show_private_data, "private");
1450         CHECK_COMPLIANCE(show_value_unit,   "unit");
1451         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
1452
1453         if (do_show_frames && do_show_packets) {
1454             av_log(wctx, AV_LOG_ERROR,
1455                    "Interleaved frames and packets are not allowed in XSD. "
1456                    "Select only one between the -show_frames and the -show_packets options.\n");
1457             return AVERROR(EINVAL);
1458         }
1459     }
1460
1461     return 0;
1462 }
1463
1464 static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1465 {
1466     const char *p;
1467
1468     for (p = src; *p; p++) {
1469         switch (*p) {
1470         case '&' : av_bprintf(dst, "%s", "&amp;");  break;
1471         case '<' : av_bprintf(dst, "%s", "&lt;");   break;
1472         case '>' : av_bprintf(dst, "%s", "&gt;");   break;
1473         case '"' : av_bprintf(dst, "%s", "&quot;"); break;
1474         case '\'': av_bprintf(dst, "%s", "&apos;"); break;
1475         default: av_bprint_chars(dst, *p, 1);
1476         }
1477     }
1478
1479     return dst->str;
1480 }
1481
1482 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1483
1484 static void xml_print_section_header(WriterContext *wctx)
1485 {
1486     XMLContext *xml = wctx->priv;
1487     const struct section *section = wctx->section[wctx->level];
1488     const struct section *parent_section = wctx->level ?
1489         wctx->section[wctx->level-1] : NULL;
1490
1491     if (wctx->level == 0) {
1492         const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1493             "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1494             "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1495
1496         printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1497         printf("<%sffprobe%s>\n",
1498                xml->fully_qualified ? "ffprobe:" : "",
1499                xml->fully_qualified ? qual : "");
1500         return;
1501     }
1502
1503     if (xml->within_tag) {
1504         xml->within_tag = 0;
1505         printf(">\n");
1506     }
1507     if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1508         xml->indent_level++;
1509     } else {
1510         if (parent_section && (parent_section->flags & SECTION_FLAG_IS_WRAPPER) &&
1511             wctx->level && wctx->nb_item[wctx->level-1])
1512             printf("\n");
1513         xml->indent_level++;
1514
1515         if (section->flags & SECTION_FLAG_IS_ARRAY) {
1516             XML_INDENT(); printf("<%s>\n", section->name);
1517         } else {
1518             XML_INDENT(); printf("<%s ", section->name);
1519             xml->within_tag = 1;
1520         }
1521     }
1522 }
1523
1524 static void xml_print_section_footer(WriterContext *wctx)
1525 {
1526     XMLContext *xml = wctx->priv;
1527     const struct section *section = wctx->section[wctx->level];
1528
1529     if (wctx->level == 0) {
1530         printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1531     } else if (xml->within_tag) {
1532         xml->within_tag = 0;
1533         printf("/>\n");
1534         xml->indent_level--;
1535     } else if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1536         xml->indent_level--;
1537     } else {
1538         XML_INDENT(); printf("</%s>\n", section->name);
1539         xml->indent_level--;
1540     }
1541 }
1542
1543 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1544 {
1545     AVBPrint buf;
1546     XMLContext *xml = wctx->priv;
1547     const struct section *section = wctx->section[wctx->level];
1548
1549     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1550
1551     if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1552         XML_INDENT();
1553         printf("<%s key=\"%s\"",
1554                section->element_name, xml_escape_str(&buf, key, wctx));
1555         av_bprint_clear(&buf);
1556         printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
1557     } else {
1558         if (wctx->nb_item[wctx->level])
1559             printf(" ");
1560         printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
1561     }
1562
1563     av_bprint_finalize(&buf, NULL);
1564 }
1565
1566 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1567 {
1568     if (wctx->nb_item[wctx->level])
1569         printf(" ");
1570     printf("%s=\"%lld\"", key, value);
1571 }
1572
1573 static Writer xml_writer = {
1574     .name                 = "xml",
1575     .priv_size            = sizeof(XMLContext),
1576     .init                 = xml_init,
1577     .print_section_header = xml_print_section_header,
1578     .print_section_footer = xml_print_section_footer,
1579     .print_integer        = xml_print_int,
1580     .print_string         = xml_print_str,
1581     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1582     .priv_class           = &xml_class,
1583 };
1584
1585 static void writer_register_all(void)
1586 {
1587     static int initialized;
1588
1589     if (initialized)
1590         return;
1591     initialized = 1;
1592
1593     writer_register(&default_writer);
1594     writer_register(&compact_writer);
1595     writer_register(&csv_writer);
1596     writer_register(&flat_writer);
1597     writer_register(&ini_writer);
1598     writer_register(&json_writer);
1599     writer_register(&xml_writer);
1600 }
1601
1602 #define print_fmt(k, f, ...) do {              \
1603     av_bprint_clear(&pbuf);                    \
1604     av_bprintf(&pbuf, f, __VA_ARGS__);         \
1605     writer_print_string(w, k, pbuf.str, 0);    \
1606 } while (0)
1607
1608 #define print_int(k, v)         writer_print_integer(w, k, v)
1609 #define print_q(k, v, s)        writer_print_rational(w, k, v, s)
1610 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1611 #define print_str_opt(k, v)     writer_print_string(w, k, v, PRINT_STRING_OPT)
1612 #define print_str_validate(k, v) writer_print_string(w, k, v, PRINT_STRING_VALIDATE)
1613 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb, 0)
1614 #define print_ts(k, v)          writer_print_ts(w, k, v, 0)
1615 #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
1616 #define print_duration_ts(k, v)       writer_print_ts(w, k, v, 1)
1617 #define print_val(k, v, u) do {                                     \
1618     struct unit_value uv;                                           \
1619     uv.val.i = v;                                                   \
1620     uv.unit = u;                                                    \
1621     writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
1622 } while (0)
1623
1624 #define print_section_header(s) writer_print_section_header(w, s)
1625 #define print_section_footer(s) writer_print_section_footer(w, s)
1626
1627 static inline int show_tags(WriterContext *w, AVDictionary *tags, int section_id)
1628 {
1629     AVDictionaryEntry *tag = NULL;
1630     int ret = 0;
1631
1632     if (!tags)
1633         return 0;
1634     writer_print_section_header(w, section_id);
1635
1636     while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1637         if ((ret = print_str_validate(tag->key, tag->value)) < 0)
1638             break;
1639     }
1640     writer_print_section_footer(w);
1641
1642     return ret;
1643 }
1644
1645 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1646 {
1647     char val_str[128];
1648     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1649     AVBPrint pbuf;
1650     const char *s;
1651
1652     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1653
1654     writer_print_section_header(w, SECTION_ID_PACKET);
1655
1656     s = av_get_media_type_string(st->codec->codec_type);
1657     if (s) print_str    ("codec_type", s);
1658     else   print_str_opt("codec_type", "unknown");
1659     print_int("stream_index",     pkt->stream_index);
1660     print_ts  ("pts",             pkt->pts);
1661     print_time("pts_time",        pkt->pts, &st->time_base);
1662     print_ts  ("dts",             pkt->dts);
1663     print_time("dts_time",        pkt->dts, &st->time_base);
1664     print_duration_ts("duration",        pkt->duration);
1665     print_duration_time("duration_time", pkt->duration, &st->time_base);
1666     print_duration_ts("convergence_duration", pkt->convergence_duration);
1667     print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
1668     print_val("size",             pkt->size, unit_byte_str);
1669     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1670     else                print_str_opt("pos", "N/A");
1671     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1672     if (do_show_data)
1673         writer_print_data(w, "data", pkt->data, pkt->size);
1674     writer_print_section_footer(w);
1675
1676     av_bprint_finalize(&pbuf, NULL);
1677     fflush(stdout);
1678 }
1679
1680 static void show_subtitle(WriterContext *w, AVSubtitle *sub, AVStream *stream,
1681                           AVFormatContext *fmt_ctx)
1682 {
1683     AVBPrint pbuf;
1684
1685     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1686
1687     writer_print_section_header(w, SECTION_ID_SUBTITLE);
1688
1689     print_str ("media_type",         "subtitle");
1690     print_ts  ("pts",                 sub->pts);
1691     print_time("pts_time",            sub->pts, &AV_TIME_BASE_Q);
1692     print_int ("format",              sub->format);
1693     print_int ("start_display_time",  sub->start_display_time);
1694     print_int ("end_display_time",    sub->end_display_time);
1695     print_int ("num_rects",           sub->num_rects);
1696
1697     writer_print_section_footer(w);
1698
1699     av_bprint_finalize(&pbuf, NULL);
1700     fflush(stdout);
1701 }
1702
1703 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
1704                        AVFormatContext *fmt_ctx)
1705 {
1706     AVBPrint pbuf;
1707     const char *s;
1708
1709     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1710
1711     writer_print_section_header(w, SECTION_ID_FRAME);
1712
1713     s = av_get_media_type_string(stream->codec->codec_type);
1714     if (s) print_str    ("media_type", s);
1715     else   print_str_opt("media_type", "unknown");
1716     print_int("key_frame",              frame->key_frame);
1717     print_ts  ("pkt_pts",               frame->pkt_pts);
1718     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1719     print_ts  ("pkt_dts",               frame->pkt_dts);
1720     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1721     print_duration_ts  ("pkt_duration",      av_frame_get_pkt_duration(frame));
1722     print_duration_time("pkt_duration_time", av_frame_get_pkt_duration(frame), &stream->time_base);
1723     if (av_frame_get_pkt_pos (frame) != -1) print_fmt    ("pkt_pos", "%"PRId64, av_frame_get_pkt_pos(frame));
1724     else                      print_str_opt("pkt_pos", "N/A");
1725     if (av_frame_get_pkt_size(frame) != -1) print_fmt    ("pkt_size", "%d", av_frame_get_pkt_size(frame));
1726     else                       print_str_opt("pkt_size", "N/A");
1727
1728     switch (stream->codec->codec_type) {
1729         AVRational sar;
1730
1731     case AVMEDIA_TYPE_VIDEO:
1732         print_int("width",                  frame->width);
1733         print_int("height",                 frame->height);
1734         s = av_get_pix_fmt_name(frame->format);
1735         if (s) print_str    ("pix_fmt", s);
1736         else   print_str_opt("pix_fmt", "unknown");
1737         sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
1738         if (sar.num) {
1739             print_q("sample_aspect_ratio", sar, ':');
1740         } else {
1741             print_str_opt("sample_aspect_ratio", "N/A");
1742         }
1743         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1744         print_int("coded_picture_number",   frame->coded_picture_number);
1745         print_int("display_picture_number", frame->display_picture_number);
1746         print_int("interlaced_frame",       frame->interlaced_frame);
1747         print_int("top_field_first",        frame->top_field_first);
1748         print_int("repeat_pict",            frame->repeat_pict);
1749         break;
1750
1751     case AVMEDIA_TYPE_AUDIO:
1752         s = av_get_sample_fmt_name(frame->format);
1753         if (s) print_str    ("sample_fmt", s);
1754         else   print_str_opt("sample_fmt", "unknown");
1755         print_int("nb_samples",         frame->nb_samples);
1756         print_int("channels", av_frame_get_channels(frame));
1757         if (av_frame_get_channel_layout(frame)) {
1758             av_bprint_clear(&pbuf);
1759             av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
1760                                      av_frame_get_channel_layout(frame));
1761             print_str    ("channel_layout", pbuf.str);
1762         } else
1763             print_str_opt("channel_layout", "unknown");
1764         break;
1765     }
1766     show_tags(w, av_frame_get_metadata(frame), SECTION_ID_FRAME_TAGS);
1767
1768     writer_print_section_footer(w);
1769
1770     av_bprint_finalize(&pbuf, NULL);
1771     fflush(stdout);
1772 }
1773
1774 static av_always_inline int process_frame(WriterContext *w,
1775                                           AVFormatContext *fmt_ctx,
1776                                           AVFrame *frame, AVPacket *pkt)
1777 {
1778     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1779     AVSubtitle sub;
1780     int ret = 0, got_frame = 0;
1781
1782     avcodec_get_frame_defaults(frame);
1783     if (dec_ctx->codec) {
1784         switch (dec_ctx->codec_type) {
1785         case AVMEDIA_TYPE_VIDEO:
1786             ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
1787             break;
1788
1789         case AVMEDIA_TYPE_AUDIO:
1790             ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
1791             break;
1792
1793         case AVMEDIA_TYPE_SUBTITLE:
1794             ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_frame, pkt);
1795             break;
1796         }
1797     }
1798
1799     if (ret < 0)
1800         return ret;
1801     ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
1802     pkt->data += ret;
1803     pkt->size -= ret;
1804     if (got_frame) {
1805         int is_sub = (dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE);
1806         nb_streams_frames[pkt->stream_index]++;
1807         if (do_show_frames)
1808             if (is_sub)
1809                 show_subtitle(w, &sub, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
1810             else
1811                 show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
1812         if (is_sub)
1813             avsubtitle_free(&sub);
1814     }
1815     return got_frame;
1816 }
1817
1818 static void log_read_interval(const ReadInterval *interval, void *log_ctx, int log_level)
1819 {
1820     av_log(log_ctx, log_level, "id:%d", interval->id);
1821
1822     if (interval->has_start) {
1823         av_log(log_ctx, log_level, " start:%s%s", interval->start_is_offset ? "+" : "",
1824                av_ts2timestr(interval->start, &AV_TIME_BASE_Q));
1825     } else {
1826         av_log(log_ctx, log_level, " start:N/A");
1827     }
1828
1829     if (interval->has_end) {
1830         av_log(log_ctx, log_level, " end:%s", interval->end_is_offset ? "+" : "");
1831         if (interval->duration_frames)
1832             av_log(log_ctx, log_level, "#%"PRId64, interval->end);
1833         else
1834             av_log(log_ctx, log_level, "%s", av_ts2timestr(interval->end, &AV_TIME_BASE_Q));
1835     } else {
1836         av_log(log_ctx, log_level, " end:N/A");
1837     }
1838
1839     av_log(log_ctx, log_level, "\n");
1840 }
1841
1842 static int read_interval_packets(WriterContext *w, AVFormatContext *fmt_ctx,
1843                                  const ReadInterval *interval, int64_t *cur_ts)
1844 {
1845     AVPacket pkt, pkt1;
1846     AVFrame frame;
1847     int ret = 0, i = 0, frame_count = 0;
1848     int64_t start = -INT64_MAX, end = interval->end;
1849     int has_start = 0, has_end = interval->has_end && !interval->end_is_offset;
1850
1851     av_init_packet(&pkt);
1852
1853     av_log(NULL, AV_LOG_VERBOSE, "Processing read interval ");
1854     log_read_interval(interval, NULL, AV_LOG_VERBOSE);
1855
1856     if (interval->has_start) {
1857         int64_t target;
1858         if (interval->start_is_offset) {
1859             if (*cur_ts == AV_NOPTS_VALUE) {
1860                 av_log(NULL, AV_LOG_ERROR,
1861                        "Could not seek to relative position since current "
1862                        "timestamp is not defined\n");
1863                 ret = AVERROR(EINVAL);
1864                 goto end;
1865             }
1866             target = *cur_ts + interval->start;
1867         } else {
1868             target = interval->start;
1869         }
1870
1871         av_log(NULL, AV_LOG_VERBOSE, "Seeking to read interval start point %s\n",
1872                av_ts2timestr(target, &AV_TIME_BASE_Q));
1873         if ((ret = avformat_seek_file(fmt_ctx, -1, -INT64_MAX, target, INT64_MAX, 0)) < 0) {
1874             av_log(NULL, AV_LOG_ERROR, "Could not seek to position %"PRId64": %s\n",
1875                    interval->start, av_err2str(ret));
1876             goto end;
1877         }
1878     }
1879
1880     while (!av_read_frame(fmt_ctx, &pkt)) {
1881         if (selected_streams[pkt.stream_index]) {
1882             AVRational tb = fmt_ctx->streams[pkt.stream_index]->time_base;
1883
1884             if (pkt.pts != AV_NOPTS_VALUE)
1885                 *cur_ts = av_rescale_q(pkt.pts, tb, AV_TIME_BASE_Q);
1886
1887             if (!has_start && *cur_ts != AV_NOPTS_VALUE) {
1888                 start = *cur_ts;
1889                 has_start = 1;
1890             }
1891
1892             if (has_start && !has_end && interval->end_is_offset) {
1893                 end = start + interval->end;
1894                 has_end = 1;
1895             }
1896
1897             if (interval->end_is_offset && interval->duration_frames) {
1898                 if (frame_count >= interval->end)
1899                     break;
1900             } else if (has_end && *cur_ts != AV_NOPTS_VALUE && *cur_ts >= end) {
1901                 break;
1902             }
1903
1904             frame_count++;
1905             if (do_read_packets) {
1906                 if (do_show_packets)
1907                     show_packet(w, fmt_ctx, &pkt, i++);
1908                 nb_streams_packets[pkt.stream_index]++;
1909             }
1910             if (do_read_frames) {
1911                 pkt1 = pkt;
1912                 while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
1913             }
1914         }
1915         av_free_packet(&pkt);
1916     }
1917     av_init_packet(&pkt);
1918     pkt.data = NULL;
1919     pkt.size = 0;
1920     //Flush remaining frames that are cached in the decoder
1921     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1922         pkt.stream_index = i;
1923         if (do_read_frames)
1924             while (process_frame(w, fmt_ctx, &frame, &pkt) > 0);
1925     }
1926
1927 end:
1928     if (ret < 0) {
1929         av_log(NULL, AV_LOG_ERROR, "Could not read packets in interval ");
1930         log_read_interval(interval, NULL, AV_LOG_ERROR);
1931     }
1932     return ret;
1933 }
1934
1935 static int read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1936 {
1937     int i, ret = 0;
1938     int64_t cur_ts = fmt_ctx->start_time;
1939
1940     if (read_intervals_nb == 0) {
1941         ReadInterval interval = (ReadInterval) { .has_start = 0, .has_end = 0 };
1942         ret = read_interval_packets(w, fmt_ctx, &interval, &cur_ts);
1943     } else {
1944         for (i = 0; i < read_intervals_nb; i++) {
1945             ret = read_interval_packets(w, fmt_ctx, &read_intervals[i], &cur_ts);
1946             if (ret < 0)
1947                 break;
1948         }
1949     }
1950
1951     return ret;
1952 }
1953
1954 static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx, int in_program)
1955 {
1956     AVStream *stream = fmt_ctx->streams[stream_idx];
1957     AVCodecContext *dec_ctx;
1958     const AVCodec *dec;
1959     char val_str[128];
1960     const char *s;
1961     AVRational sar, dar;
1962     AVBPrint pbuf;
1963     int ret = 0;
1964
1965     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1966
1967     writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM : SECTION_ID_STREAM);
1968
1969     print_int("index", stream->index);
1970
1971     if ((dec_ctx = stream->codec)) {
1972         const char *profile = NULL;
1973         dec = dec_ctx->codec;
1974         if (dec) {
1975             print_str("codec_name", dec->name);
1976             if (!do_bitexact) {
1977                 if (dec->long_name) print_str    ("codec_long_name", dec->long_name);
1978                 else                print_str_opt("codec_long_name", "unknown");
1979             }
1980         } else {
1981             print_str_opt("codec_name", "unknown");
1982             if (!do_bitexact) {
1983                 print_str_opt("codec_long_name", "unknown");
1984             }
1985         }
1986
1987         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
1988             print_str("profile", profile);
1989         else
1990             print_str_opt("profile", "unknown");
1991
1992         s = av_get_media_type_string(dec_ctx->codec_type);
1993         if (s) print_str    ("codec_type", s);
1994         else   print_str_opt("codec_type", "unknown");
1995         print_q("codec_time_base", dec_ctx->time_base, '/');
1996
1997         /* print AVI/FourCC tag */
1998         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1999         print_str("codec_tag_string",    val_str);
2000         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
2001
2002         switch (dec_ctx->codec_type) {
2003         case AVMEDIA_TYPE_VIDEO:
2004             print_int("width",        dec_ctx->width);
2005             print_int("height",       dec_ctx->height);
2006             print_int("has_b_frames", dec_ctx->has_b_frames);
2007             sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
2008             if (sar.den) {
2009                 print_q("sample_aspect_ratio", sar, ':');
2010                 av_reduce(&dar.num, &dar.den,
2011                           dec_ctx->width  * sar.num,
2012                           dec_ctx->height * sar.den,
2013                           1024*1024);
2014                 print_q("display_aspect_ratio", dar, ':');
2015             } else {
2016                 print_str_opt("sample_aspect_ratio", "N/A");
2017                 print_str_opt("display_aspect_ratio", "N/A");
2018             }
2019             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
2020             if (s) print_str    ("pix_fmt", s);
2021             else   print_str_opt("pix_fmt", "unknown");
2022             print_int("level",   dec_ctx->level);
2023             if (dec_ctx->timecode_frame_start >= 0) {
2024                 char tcbuf[AV_TIMECODE_STR_SIZE];
2025                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
2026                 print_str("timecode", tcbuf);
2027             } else {
2028                 print_str_opt("timecode", "N/A");
2029             }
2030             break;
2031
2032         case AVMEDIA_TYPE_AUDIO:
2033             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
2034             if (s) print_str    ("sample_fmt", s);
2035             else   print_str_opt("sample_fmt", "unknown");
2036             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
2037             print_int("channels",        dec_ctx->channels);
2038
2039             if (dec_ctx->channel_layout) {
2040                 av_bprint_clear(&pbuf);
2041                 av_bprint_channel_layout(&pbuf, dec_ctx->channels, dec_ctx->channel_layout);
2042                 print_str    ("channel_layout", pbuf.str);
2043             } else {
2044                 print_str_opt("channel_layout", "unknown");
2045             }
2046
2047             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
2048             break;
2049
2050         case AVMEDIA_TYPE_SUBTITLE:
2051             if (dec_ctx->width)
2052                 print_int("width",       dec_ctx->width);
2053             else
2054                 print_str_opt("width",   "N/A");
2055             if (dec_ctx->height)
2056                 print_int("height",      dec_ctx->height);
2057             else
2058                 print_str_opt("height",  "N/A");
2059             break;
2060         }
2061     } else {
2062         print_str_opt("codec_type", "unknown");
2063     }
2064     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
2065         const AVOption *opt = NULL;
2066         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
2067             uint8_t *str;
2068             if (opt->flags) continue;
2069             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
2070                 print_str(opt->name, str);
2071                 av_free(str);
2072             }
2073         }
2074     }
2075
2076     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
2077     else                                          print_str_opt("id", "N/A");
2078     print_q("r_frame_rate",   stream->r_frame_rate,   '/');
2079     print_q("avg_frame_rate", stream->avg_frame_rate, '/');
2080     print_q("time_base",      stream->time_base,      '/');
2081     print_ts  ("start_pts",   stream->start_time);
2082     print_time("start_time",  stream->start_time, &stream->time_base);
2083     print_ts  ("duration_ts", stream->duration);
2084     print_time("duration",    stream->duration, &stream->time_base);
2085     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
2086     else                       print_str_opt("bit_rate", "N/A");
2087     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
2088     else                   print_str_opt("nb_frames", "N/A");
2089     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
2090     else                                print_str_opt("nb_read_frames", "N/A");
2091     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
2092     else                                print_str_opt("nb_read_packets", "N/A");
2093     if (do_show_data)
2094         writer_print_data(w, "extradata", dec_ctx->extradata,
2095                                           dec_ctx->extradata_size);
2096
2097     /* Print disposition information */
2098 #define PRINT_DISPOSITION(flagname, name) do {                                \
2099         print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
2100     } while (0)
2101
2102     if (do_show_stream_disposition) {
2103     writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM_DISPOSITION : SECTION_ID_STREAM_DISPOSITION);
2104     PRINT_DISPOSITION(DEFAULT,          "default");
2105     PRINT_DISPOSITION(DUB,              "dub");
2106     PRINT_DISPOSITION(ORIGINAL,         "original");
2107     PRINT_DISPOSITION(COMMENT,          "comment");
2108     PRINT_DISPOSITION(LYRICS,           "lyrics");
2109     PRINT_DISPOSITION(KARAOKE,          "karaoke");
2110     PRINT_DISPOSITION(FORCED,           "forced");
2111     PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");
2112     PRINT_DISPOSITION(VISUAL_IMPAIRED,  "visual_impaired");
2113     PRINT_DISPOSITION(CLEAN_EFFECTS,    "clean_effects");
2114     PRINT_DISPOSITION(ATTACHED_PIC,     "attached_pic");
2115     writer_print_section_footer(w);
2116     }
2117
2118     ret = show_tags(w, stream->metadata, in_program ? SECTION_ID_PROGRAM_STREAM_TAGS : SECTION_ID_STREAM_TAGS);
2119
2120     writer_print_section_footer(w);
2121     av_bprint_finalize(&pbuf, NULL);
2122     fflush(stdout);
2123
2124     return ret;
2125 }
2126
2127 static int show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
2128 {
2129     int i, ret = 0;
2130
2131     writer_print_section_header(w, SECTION_ID_STREAMS);
2132     for (i = 0; i < fmt_ctx->nb_streams; i++)
2133         if (selected_streams[i]) {
2134             ret = show_stream(w, fmt_ctx, i, 0);
2135             if (ret < 0)
2136                 break;
2137         }
2138     writer_print_section_footer(w);
2139
2140     return ret;
2141 }
2142
2143 static int show_program(WriterContext *w, AVFormatContext *fmt_ctx, AVProgram *program)
2144 {
2145     int i, ret = 0;
2146
2147     writer_print_section_header(w, SECTION_ID_PROGRAM);
2148     print_int("program_id", program->id);
2149     print_int("program_num", program->program_num);
2150     print_int("nb_streams", program->nb_stream_indexes);
2151     print_int("pmt_pid", program->pmt_pid);
2152     print_int("pcr_pid", program->pcr_pid);
2153     print_ts("start_pts", program->start_time);
2154     print_time("start_time", program->start_time, &AV_TIME_BASE_Q);
2155     print_ts("end_pts", program->end_time);
2156     print_time("end_time", program->end_time, &AV_TIME_BASE_Q);
2157     ret = show_tags(w, program->metadata, SECTION_ID_PROGRAM_TAGS);
2158     if (ret < 0)
2159         goto end;
2160
2161     writer_print_section_header(w, SECTION_ID_PROGRAM_STREAMS);
2162     for (i = 0; i < program->nb_stream_indexes; i++) {
2163         if (selected_streams[program->stream_index[i]]) {
2164             ret = show_stream(w, fmt_ctx, program->stream_index[i], 1);
2165             if (ret < 0)
2166                 break;
2167         }
2168     }
2169     writer_print_section_footer(w);
2170
2171 end:
2172     writer_print_section_footer(w);
2173     return ret;
2174 }
2175
2176 static int show_programs(WriterContext *w, AVFormatContext *fmt_ctx)
2177 {
2178     int i, ret = 0;
2179
2180     writer_print_section_header(w, SECTION_ID_PROGRAMS);
2181     for (i = 0; i < fmt_ctx->nb_programs; i++) {
2182         AVProgram *program = fmt_ctx->programs[i];
2183         if (!program)
2184             continue;
2185         ret = show_program(w, fmt_ctx, program);
2186         if (ret < 0)
2187             break;
2188     }
2189     writer_print_section_footer(w);
2190     return ret;
2191 }
2192
2193 static int show_chapters(WriterContext *w, AVFormatContext *fmt_ctx)
2194 {
2195     int i, ret = 0;
2196
2197     writer_print_section_header(w, SECTION_ID_CHAPTERS);
2198     for (i = 0; i < fmt_ctx->nb_chapters; i++) {
2199         AVChapter *chapter = fmt_ctx->chapters[i];
2200
2201         writer_print_section_header(w, SECTION_ID_CHAPTER);
2202         print_int("id", chapter->id);
2203         print_q  ("time_base", chapter->time_base, '/');
2204         print_int("start", chapter->start);
2205         print_time("start_time", chapter->start, &chapter->time_base);
2206         print_int("end", chapter->end);
2207         print_time("end_time", chapter->end, &chapter->time_base);
2208         ret = show_tags(w, chapter->metadata, SECTION_ID_CHAPTER_TAGS);
2209         writer_print_section_footer(w);
2210     }
2211     writer_print_section_footer(w);
2212
2213     return ret;
2214 }
2215
2216 static int show_format(WriterContext *w, AVFormatContext *fmt_ctx)
2217 {
2218     char val_str[128];
2219     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
2220     int ret = 0;
2221
2222     writer_print_section_header(w, SECTION_ID_FORMAT);
2223     print_str_validate("filename", fmt_ctx->filename);
2224     print_int("nb_streams",       fmt_ctx->nb_streams);
2225     print_int("nb_programs",      fmt_ctx->nb_programs);
2226     print_str("format_name",      fmt_ctx->iformat->name);
2227     if (!do_bitexact) {
2228         if (fmt_ctx->iformat->long_name) print_str    ("format_long_name", fmt_ctx->iformat->long_name);
2229         else                             print_str_opt("format_long_name", "unknown");
2230     }
2231     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
2232     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
2233     if (size >= 0) print_val    ("size", size, unit_byte_str);
2234     else           print_str_opt("size", "N/A");
2235     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
2236     else                       print_str_opt("bit_rate", "N/A");
2237     print_int("probe_score", av_format_get_probe_score(fmt_ctx));
2238     ret = show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
2239
2240     writer_print_section_footer(w);
2241     fflush(stdout);
2242     return ret;
2243 }
2244
2245 static void show_error(WriterContext *w, int err)
2246 {
2247     char errbuf[128];
2248     const char *errbuf_ptr = errbuf;
2249
2250     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
2251         errbuf_ptr = strerror(AVUNERROR(err));
2252
2253     writer_print_section_header(w, SECTION_ID_ERROR);
2254     print_int("code", err);
2255     print_str("string", errbuf_ptr);
2256     writer_print_section_footer(w);
2257 }
2258
2259 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
2260 {
2261     int err, i, orig_nb_streams;
2262     AVFormatContext *fmt_ctx = NULL;
2263     AVDictionaryEntry *t;
2264     AVDictionary **opts;
2265
2266     if ((err = avformat_open_input(&fmt_ctx, filename,
2267                                    iformat, &format_opts)) < 0) {
2268         print_error(filename, err);
2269         return err;
2270     }
2271     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2272         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
2273         return AVERROR_OPTION_NOT_FOUND;
2274     }
2275
2276     /* fill the streams in the format context */
2277     opts = setup_find_stream_info_opts(fmt_ctx, codec_opts);
2278     orig_nb_streams = fmt_ctx->nb_streams;
2279
2280     if ((err = avformat_find_stream_info(fmt_ctx, opts)) < 0) {
2281         print_error(filename, err);
2282         return err;
2283     }
2284     for (i = 0; i < orig_nb_streams; i++)
2285         av_dict_free(&opts[i]);
2286     av_freep(&opts);
2287
2288     av_dump_format(fmt_ctx, 0, filename, 0);
2289
2290     /* bind a decoder to each input stream */
2291     for (i = 0; i < fmt_ctx->nb_streams; i++) {
2292         AVStream *stream = fmt_ctx->streams[i];
2293         AVCodec *codec;
2294
2295         if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
2296             av_log(NULL, AV_LOG_WARNING,
2297                    "Failed to probe codec for input stream %d\n",
2298                     stream->index);
2299         } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
2300             av_log(NULL, AV_LOG_WARNING,
2301                     "Unsupported codec with id %d for input stream %d\n",
2302                     stream->codec->codec_id, stream->index);
2303         } else {
2304             AVDictionary *opts = filter_codec_opts(codec_opts, stream->codec->codec_id,
2305                                                    fmt_ctx, stream, codec);
2306             if (avcodec_open2(stream->codec, codec, &opts) < 0) {
2307                 av_log(NULL, AV_LOG_WARNING, "Could not open codec for input stream %d\n",
2308                        stream->index);
2309             }
2310             if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
2311                 av_log(NULL, AV_LOG_ERROR, "Option %s for input stream %d not found\n",
2312                        t->key, stream->index);
2313                 return AVERROR_OPTION_NOT_FOUND;
2314             }
2315         }
2316     }
2317
2318     *fmt_ctx_ptr = fmt_ctx;
2319     return 0;
2320 }
2321
2322 static void close_input_file(AVFormatContext **ctx_ptr)
2323 {
2324     int i;
2325     AVFormatContext *fmt_ctx = *ctx_ptr;
2326
2327     /* close decoder for each stream */
2328     for (i = 0; i < fmt_ctx->nb_streams; i++)
2329         if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
2330             avcodec_close(fmt_ctx->streams[i]->codec);
2331
2332     avformat_close_input(ctx_ptr);
2333 }
2334
2335 static int probe_file(WriterContext *wctx, const char *filename)
2336 {
2337     AVFormatContext *fmt_ctx;
2338     int ret, i;
2339     int section_id;
2340
2341     do_read_frames = do_show_frames || do_count_frames;
2342     do_read_packets = do_show_packets || do_count_packets;
2343
2344     ret = open_input_file(&fmt_ctx, filename);
2345     if (ret < 0)
2346         return ret;
2347
2348 #define CHECK_END if (ret < 0) goto end
2349
2350     nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
2351     nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
2352     selected_streams   = av_calloc(fmt_ctx->nb_streams, sizeof(*selected_streams));
2353
2354     for (i = 0; i < fmt_ctx->nb_streams; i++) {
2355         if (stream_specifier) {
2356             ret = avformat_match_stream_specifier(fmt_ctx,
2357                                                   fmt_ctx->streams[i],
2358                                                   stream_specifier);
2359             CHECK_END;
2360             else
2361                 selected_streams[i] = ret;
2362             ret = 0;
2363         } else {
2364             selected_streams[i] = 1;
2365         }
2366     }
2367
2368     if (do_read_frames || do_read_packets) {
2369         if (do_show_frames && do_show_packets &&
2370             wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
2371             section_id = SECTION_ID_PACKETS_AND_FRAMES;
2372         else if (do_show_packets && !do_show_frames)
2373             section_id = SECTION_ID_PACKETS;
2374         else // (!do_show_packets && do_show_frames)
2375             section_id = SECTION_ID_FRAMES;
2376         if (do_show_frames || do_show_packets)
2377             writer_print_section_header(wctx, section_id);
2378         ret = read_packets(wctx, fmt_ctx);
2379         if (do_show_frames || do_show_packets)
2380             writer_print_section_footer(wctx);
2381         CHECK_END;
2382     }
2383     if (do_show_programs) {
2384         ret = show_programs(wctx, fmt_ctx);
2385         CHECK_END;
2386     }
2387
2388     if (do_show_streams) {
2389         ret = show_streams(wctx, fmt_ctx);
2390         CHECK_END;
2391     }
2392     if (do_show_chapters) {
2393         ret = show_chapters(wctx, fmt_ctx);
2394         CHECK_END;
2395     }
2396     if (do_show_format) {
2397         ret = show_format(wctx, fmt_ctx);
2398         CHECK_END;
2399     }
2400
2401 end:
2402     close_input_file(&fmt_ctx);
2403     av_freep(&nb_streams_frames);
2404     av_freep(&nb_streams_packets);
2405     av_freep(&selected_streams);
2406
2407     return ret;
2408 }
2409
2410 static void show_usage(void)
2411 {
2412     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
2413     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
2414     av_log(NULL, AV_LOG_INFO, "\n");
2415 }
2416
2417 static void ffprobe_show_program_version(WriterContext *w)
2418 {
2419     AVBPrint pbuf;
2420     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
2421
2422     writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
2423     print_str("version", FFMPEG_VERSION);
2424     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
2425               program_birth_year, CONFIG_THIS_YEAR);
2426     print_str("build_date", __DATE__);
2427     print_str("build_time", __TIME__);
2428     print_str("compiler_ident", CC_IDENT);
2429     print_str("configuration", FFMPEG_CONFIGURATION);
2430     writer_print_section_footer(w);
2431
2432     av_bprint_finalize(&pbuf, NULL);
2433 }
2434
2435 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
2436     do {                                                                \
2437         if (CONFIG_##LIBNAME) {                                         \
2438             unsigned int version = libname##_version();                 \
2439             writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
2440             print_str("name",    "lib" #libname);                       \
2441             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
2442             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
2443             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
2444             print_int("version", version);                              \
2445             print_str("ident",   LIB##LIBNAME##_IDENT);                 \
2446             writer_print_section_footer(w);                             \
2447         }                                                               \
2448     } while (0)
2449
2450 static void ffprobe_show_library_versions(WriterContext *w)
2451 {
2452     writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
2453     SHOW_LIB_VERSION(avutil,     AVUTIL);
2454     SHOW_LIB_VERSION(avcodec,    AVCODEC);
2455     SHOW_LIB_VERSION(avformat,   AVFORMAT);
2456     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
2457     SHOW_LIB_VERSION(avfilter,   AVFILTER);
2458     SHOW_LIB_VERSION(swscale,    SWSCALE);
2459     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
2460     SHOW_LIB_VERSION(postproc,   POSTPROC);
2461     writer_print_section_footer(w);
2462 }
2463
2464 static int opt_format(void *optctx, const char *opt, const char *arg)
2465 {
2466     iformat = av_find_input_format(arg);
2467     if (!iformat) {
2468         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
2469         return AVERROR(EINVAL);
2470     }
2471     return 0;
2472 }
2473
2474 static inline void mark_section_show_entries(SectionID section_id,
2475                                              int show_all_entries, AVDictionary *entries)
2476 {
2477     struct section *section = &sections[section_id];
2478
2479     section->show_all_entries = show_all_entries;
2480     if (show_all_entries) {
2481         SectionID *id;
2482         for (id = section->children_ids; *id != -1; id++)
2483             mark_section_show_entries(*id, show_all_entries, entries);
2484     } else {
2485         av_dict_copy(&section->entries_to_show, entries, 0);
2486     }
2487 }
2488
2489 static int match_section(const char *section_name,
2490                          int show_all_entries, AVDictionary *entries)
2491 {
2492     int i, ret = 0;
2493
2494     for (i = 0; i < FF_ARRAY_ELEMS(sections); i++) {
2495         const struct section *section = &sections[i];
2496         if (!strcmp(section_name, section->name) ||
2497             (section->unique_name && !strcmp(section_name, section->unique_name))) {
2498             av_log(NULL, AV_LOG_DEBUG,
2499                    "'%s' matches section with unique name '%s'\n", section_name,
2500                    (char *)av_x_if_null(section->unique_name, section->name));
2501             ret++;
2502             mark_section_show_entries(section->id, show_all_entries, entries);
2503         }
2504     }
2505     return ret;
2506 }
2507
2508 static int opt_show_entries(void *optctx, const char *opt, const char *arg)
2509 {
2510     const char *p = arg;
2511     int ret = 0;
2512
2513     while (*p) {
2514         AVDictionary *entries = NULL;
2515         char *section_name = av_get_token(&p, "=:");
2516         int show_all_entries = 0;
2517
2518         if (!section_name) {
2519             av_log(NULL, AV_LOG_ERROR,
2520                    "Missing section name for option '%s'\n", opt);
2521             return AVERROR(EINVAL);
2522         }
2523
2524         if (*p == '=') {
2525             p++;
2526             while (*p && *p != ':') {
2527                 char *entry = av_get_token(&p, ",:");
2528                 if (!entry)
2529                     break;
2530                 av_log(NULL, AV_LOG_VERBOSE,
2531                        "Adding '%s' to the entries to show in section '%s'\n",
2532                        entry, section_name);
2533                 av_dict_set(&entries, entry, "", AV_DICT_DONT_STRDUP_KEY);
2534                 if (*p == ',')
2535                     p++;
2536             }
2537         } else {
2538             show_all_entries = 1;
2539         }
2540
2541         ret = match_section(section_name, show_all_entries, entries);
2542         if (ret == 0) {
2543             av_log(NULL, AV_LOG_ERROR, "No match for section '%s'\n", section_name);
2544             ret = AVERROR(EINVAL);
2545         }
2546         av_dict_free(&entries);
2547         av_free(section_name);
2548
2549         if (ret <= 0)
2550             break;
2551         if (*p)
2552             p++;
2553     }
2554
2555     return ret;
2556 }
2557
2558 static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
2559 {
2560     char *buf = av_asprintf("format=%s", arg);
2561     int ret;
2562
2563     av_log(NULL, AV_LOG_WARNING,
2564            "Option '%s' is deprecated, use '-show_entries format=%s' instead\n",
2565            opt, arg);
2566     ret = opt_show_entries(optctx, opt, buf);
2567     av_free(buf);
2568     return ret;
2569 }
2570
2571 static void opt_input_file(void *optctx, const char *arg)
2572 {
2573     if (input_filename) {
2574         av_log(NULL, AV_LOG_ERROR,
2575                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
2576                 arg, input_filename);
2577         exit_program(1);
2578     }
2579     if (!strcmp(arg, "-"))
2580         arg = "pipe:";
2581     input_filename = arg;
2582 }
2583
2584 static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
2585 {
2586     opt_input_file(optctx, arg);
2587     return 0;
2588 }
2589
2590 void show_help_default(const char *opt, const char *arg)
2591 {
2592     av_log_set_callback(log_callback_help);
2593     show_usage();
2594     show_help_options(options, "Main options:", 0, 0, 0);
2595     printf("\n");
2596
2597     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
2598 }
2599
2600 /**
2601  * Parse interval specification, according to the format:
2602  * INTERVAL ::= [START|+START_OFFSET][%[END|+END_OFFSET]]
2603  * INTERVALS ::= INTERVAL[,INTERVALS]
2604 */
2605 static int parse_read_interval(const char *interval_spec,
2606                                ReadInterval *interval)
2607 {
2608     int ret = 0;
2609     char *next, *p, *spec = av_strdup(interval_spec);
2610     if (!spec)
2611         return AVERROR(ENOMEM);
2612
2613     if (!*spec) {
2614         av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n");
2615         ret = AVERROR(EINVAL);
2616         goto end;
2617     }
2618
2619     p = spec;
2620     next = strchr(spec, '%');
2621     if (next)
2622         *next++ = 0;
2623
2624     /* parse first part */
2625     if (*p) {
2626         interval->has_start = 1;
2627
2628         if (*p == '+') {
2629             interval->start_is_offset = 1;
2630             p++;
2631         } else {
2632             interval->start_is_offset = 0;
2633         }
2634
2635         ret = av_parse_time(&interval->start, p, 1);
2636         if (ret < 0) {
2637             av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p);
2638             goto end;
2639         }
2640     } else {
2641         interval->has_start = 0;
2642     }
2643
2644     /* parse second part */
2645     p = next;
2646     if (p && *p) {
2647         int64_t us;
2648         interval->has_end = 1;
2649
2650         if (*p == '+') {
2651             interval->end_is_offset = 1;
2652             p++;
2653         } else {
2654             interval->end_is_offset = 0;
2655         }
2656
2657         if (interval->end_is_offset && *p == '#') {
2658             long long int lli;
2659             char *tail;
2660             interval->duration_frames = 1;
2661             p++;
2662             lli = strtoll(p, &tail, 10);
2663             if (*tail || lli < 0) {
2664                 av_log(NULL, AV_LOG_ERROR,
2665                        "Invalid or negative value '%s' for duration number of frames\n", p);
2666                 goto end;
2667             }
2668             interval->end = lli;
2669         } else {
2670             ret = av_parse_time(&us, p, 1);
2671             if (ret < 0) {
2672                 av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p);
2673                 goto end;
2674             }
2675             interval->end = us;
2676         }
2677     } else {
2678         interval->has_end = 0;
2679     }
2680
2681 end:
2682     av_free(spec);
2683     return ret;
2684 }
2685
2686 static int parse_read_intervals(const char *intervals_spec)
2687 {
2688     int ret, n, i;
2689     char *p, *spec = av_strdup(intervals_spec);
2690     if (!spec)
2691         return AVERROR(ENOMEM);
2692
2693     /* preparse specification, get number of intervals */
2694     for (n = 0, p = spec; *p; p++)
2695         if (*p == ',')
2696             n++;
2697     n++;
2698
2699     read_intervals = av_malloc(n * sizeof(*read_intervals));
2700     if (!read_intervals) {
2701         ret = AVERROR(ENOMEM);
2702         goto end;
2703     }
2704     read_intervals_nb = n;
2705
2706     /* parse intervals */
2707     p = spec;
2708     for (i = 0; p; i++) {
2709         char *next;
2710
2711         av_assert0(i < read_intervals_nb);
2712         next = strchr(p, ',');
2713         if (next)
2714             *next++ = 0;
2715
2716         read_intervals[i].id = i;
2717         ret = parse_read_interval(p, &read_intervals[i]);
2718         if (ret < 0) {
2719             av_log(NULL, AV_LOG_ERROR, "Error parsing read interval #%d '%s'\n",
2720                    i, p);
2721             goto end;
2722         }
2723         av_log(NULL, AV_LOG_VERBOSE, "Parsed log interval ");
2724         log_read_interval(&read_intervals[i], NULL, AV_LOG_VERBOSE);
2725         p = next;
2726     }
2727     av_assert0(i == read_intervals_nb);
2728
2729 end:
2730     av_free(spec);
2731     return ret;
2732 }
2733
2734 static int opt_read_intervals(void *optctx, const char *opt, const char *arg)
2735 {
2736     return parse_read_intervals(arg);
2737 }
2738
2739 static int opt_pretty(void *optctx, const char *opt, const char *arg)
2740 {
2741     show_value_unit              = 1;
2742     use_value_prefix             = 1;
2743     use_byte_value_binary_prefix = 1;
2744     use_value_sexagesimal_format = 1;
2745     return 0;
2746 }
2747
2748 static void print_section(SectionID id, int level)
2749 {
2750     const SectionID *pid;
2751     const struct section *section = &sections[id];
2752     printf("%c%c%c",
2753            section->flags & SECTION_FLAG_IS_WRAPPER           ? 'W' : '.',
2754            section->flags & SECTION_FLAG_IS_ARRAY             ? 'A' : '.',
2755            section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS  ? 'V' : '.');
2756     printf("%*c  %s", level * 4, ' ', section->name);
2757     if (section->unique_name)
2758         printf("/%s", section->unique_name);
2759     printf("\n");
2760
2761     for (pid = section->children_ids; *pid != -1; pid++)
2762         print_section(*pid, level+1);
2763 }
2764
2765 static int opt_sections(void *optctx, const char *opt, const char *arg)
2766 {
2767     printf("Sections:\n"
2768            "W.. = Section is a wrapper (contains other sections, no local entries)\n"
2769            ".A. = Section contains an array of elements of the same type\n"
2770            "..V = Section may contain a variable number of fields with variable keys\n"
2771            "FLAGS NAME/UNIQUE_NAME\n"
2772            "---\n");
2773     print_section(SECTION_ID_ROOT, 0);
2774     return 0;
2775 }
2776
2777 static int opt_show_versions(const char *opt, const char *arg)
2778 {
2779     mark_section_show_entries(SECTION_ID_PROGRAM_VERSION, 1, NULL);
2780     mark_section_show_entries(SECTION_ID_LIBRARY_VERSION, 1, NULL);
2781     return 0;
2782 }
2783
2784 #define DEFINE_OPT_SHOW_SECTION(section, target_section_id)             \
2785     static int opt_show_##section(const char *opt, const char *arg)     \
2786     {                                                                   \
2787         mark_section_show_entries(SECTION_ID_##target_section_id, 1, NULL); \
2788         return 0;                                                       \
2789     }
2790
2791 DEFINE_OPT_SHOW_SECTION(chapters,         CHAPTERS);
2792 DEFINE_OPT_SHOW_SECTION(error,            ERROR);
2793 DEFINE_OPT_SHOW_SECTION(format,           FORMAT);
2794 DEFINE_OPT_SHOW_SECTION(frames,           FRAMES);
2795 DEFINE_OPT_SHOW_SECTION(library_versions, LIBRARY_VERSIONS);
2796 DEFINE_OPT_SHOW_SECTION(packets,          PACKETS);
2797 DEFINE_OPT_SHOW_SECTION(program_version,  PROGRAM_VERSION);
2798 DEFINE_OPT_SHOW_SECTION(streams,          STREAMS);
2799 DEFINE_OPT_SHOW_SECTION(programs,         PROGRAMS);
2800
2801 static const OptionDef real_options[] = {
2802 #include "cmdutils_common_opts.h"
2803     { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
2804     { "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
2805     { "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
2806     { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
2807       "use binary prefixes for byte units" },
2808     { "sexagesimal", OPT_BOOL,  {&use_value_sexagesimal_format},
2809       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
2810     { "pretty", 0, {.func_arg = opt_pretty},
2811       "prettify the format of displayed values, make it more human readable" },
2812     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
2813       "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
2814     { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
2815     { "select_streams", OPT_STRING | HAS_ARG, {(void*)&stream_specifier}, "select the specified streams", "stream_specifier" },
2816     { "sections", OPT_EXIT, {.func_arg = opt_sections}, "print sections structure and section information, and exit" },
2817     { "show_data",    OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
2818     { "show_error",   0, {(void*)&opt_show_error},  "show probing error" },
2819     { "show_format",  0, {(void*)&opt_show_format}, "show format/container info" },
2820     { "show_frames",  0, {(void*)&opt_show_frames}, "show frames info" },
2821     { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
2822       "show a particular entry from the format/container info", "entry" },
2823     { "show_entries", HAS_ARG, {.func_arg = opt_show_entries},
2824       "show a set of specified entries", "entry_list" },
2825     { "show_packets", 0, {(void*)&opt_show_packets}, "show packets info" },
2826     { "show_programs", 0, {(void*)&opt_show_programs}, "show programs info" },
2827     { "show_streams", 0, {(void*)&opt_show_streams}, "show streams info" },
2828     { "show_chapters", 0, {(void*)&opt_show_chapters}, "show chapters info" },
2829     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
2830     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
2831     { "show_program_version",  0, {(void*)&opt_show_program_version},  "show ffprobe version" },
2832     { "show_library_versions", 0, {(void*)&opt_show_library_versions}, "show library versions" },
2833     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
2834     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
2835     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
2836     { "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
2837     { "read_intervals", HAS_ARG, {.func_arg = opt_read_intervals}, "set read intervals", "read_intervals" },
2838     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
2839     { "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
2840     { NULL, },
2841 };
2842
2843 static inline int check_section_show_entries(int section_id)
2844 {
2845     int *id;
2846     struct section *section = &sections[section_id];
2847     if (sections[section_id].show_all_entries || sections[section_id].entries_to_show)
2848         return 1;
2849     for (id = section->children_ids; *id != -1; id++)
2850         if (check_section_show_entries(*id))
2851             return 1;
2852     return 0;
2853 }
2854
2855 #define SET_DO_SHOW(id, varname) do {                                   \
2856         if (check_section_show_entries(SECTION_ID_##id))                \
2857             do_show_##varname = 1;                                      \
2858     } while (0)
2859
2860 int main(int argc, char **argv)
2861 {
2862     const Writer *w;
2863     WriterContext *wctx;
2864     char *buf;
2865     char *w_name = NULL, *w_args = NULL;
2866     int ret, i;
2867
2868     av_log_set_flags(AV_LOG_SKIP_REPEATED);
2869     register_exit(ffprobe_cleanup);
2870
2871     options = real_options;
2872     parse_loglevel(argc, argv, options);
2873     av_register_all();
2874     avformat_network_init();
2875     init_opts();
2876 #if CONFIG_AVDEVICE
2877     avdevice_register_all();
2878 #endif
2879
2880     show_banner(argc, argv, options);
2881     parse_options(NULL, argc, argv, options, opt_input_file);
2882
2883     /* mark things to show, based on -show_entries */
2884     SET_DO_SHOW(CHAPTERS, chapters);
2885     SET_DO_SHOW(ERROR, error);
2886     SET_DO_SHOW(FORMAT, format);
2887     SET_DO_SHOW(FRAMES, frames);
2888     SET_DO_SHOW(LIBRARY_VERSIONS, library_versions);
2889     SET_DO_SHOW(PACKETS, packets);
2890     SET_DO_SHOW(PROGRAM_VERSION, program_version);
2891     SET_DO_SHOW(PROGRAMS, programs);
2892     SET_DO_SHOW(STREAMS, streams);
2893     SET_DO_SHOW(STREAM_DISPOSITION, stream_disposition);
2894     SET_DO_SHOW(PROGRAM_STREAM_DISPOSITION, stream_disposition);
2895
2896     if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
2897         av_log(NULL, AV_LOG_ERROR,
2898                "-bitexact and -show_program_version or -show_library_versions "
2899                "options are incompatible\n");
2900         ret = AVERROR(EINVAL);
2901         goto end;
2902     }
2903
2904     writer_register_all();
2905
2906     if (!print_format)
2907         print_format = av_strdup("default");
2908     if (!print_format) {
2909         ret = AVERROR(ENOMEM);
2910         goto end;
2911     }
2912     w_name = av_strtok(print_format, "=", &buf);
2913     w_args = buf;
2914
2915     w = writer_get_by_name(w_name);
2916     if (!w) {
2917         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
2918         ret = AVERROR(EINVAL);
2919         goto end;
2920     }
2921
2922     if ((ret = writer_open(&wctx, w, w_args,
2923                            sections, FF_ARRAY_ELEMS(sections))) >= 0) {
2924         if (w == &xml_writer)
2925             wctx->string_validation_utf8_flags |= AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES;
2926
2927         writer_print_section_header(wctx, SECTION_ID_ROOT);
2928
2929         if (do_show_program_version)
2930             ffprobe_show_program_version(wctx);
2931         if (do_show_library_versions)
2932             ffprobe_show_library_versions(wctx);
2933
2934         if (!input_filename &&
2935             ((do_show_format || do_show_programs || do_show_streams || do_show_chapters || do_show_packets || do_show_error) ||
2936              (!do_show_program_version && !do_show_library_versions))) {
2937             show_usage();
2938             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
2939             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
2940             ret = AVERROR(EINVAL);
2941         } else if (input_filename) {
2942             ret = probe_file(wctx, input_filename);
2943             if (ret < 0 && do_show_error)
2944                 show_error(wctx, ret);
2945         }
2946
2947         writer_print_section_footer(wctx);
2948         writer_close(&wctx);
2949     }
2950
2951 end:
2952     av_freep(&print_format);
2953     av_freep(&read_intervals);
2954
2955     uninit_opts();
2956     for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
2957         av_dict_free(&(sections[i].entries_to_show));
2958
2959     avformat_network_deinit();
2960
2961     return ret < 0;
2962 }