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