OSDN Git Service

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